问题描述:

class International(object):

""" International Class that stores versions and lists

countries

"""

def __init__(self, version, countrylist):

self.version = version

self.country_list = countrylist

class InternationalSerializer(serializers.Serializer):

""" Serializer for International page

Lists International countries and current version

"""

version = serializers.IntegerField(read_only=True)

country_list = CountrySerializer(many=True, read_only=True)

I have a serializer set up this way, and I wish to display serialized.data (which will be a dictionary like this: { "version": xx, and "country_list": [ ] } ) using views.py

I have my views.py setup this way:

class CountryListView(generics.ListAPIView):

""" Endpoint : somedomain/international/

"""

## want to display a dictionary like the one below

{

"version": 5

"country_list" : [ { xxx } , { xxx } , { xxx } ]

}

What do I code in this CountryListView to render a dictionary like the one above? I'm really unsure.

网友答案:

Try this

 class CountryListView(generics.ListAPIView):
        """ Endpoint : somedomain/international/
        """

       def get(self,request):

          #get your version and country_list data and
          #init your object
          international_object = International(version,country_list)
          serializer = InternationalSerializer(instance=international_object)
          your_data = serializer.data
          return your_data
网友答案:

You can build on the idea from here: http://www.django-rest-framework.org/api-guide/pagination/#example

Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:

class CustomPagination(pagination.PageNumberPagination):
    def get_paginated_response(self, data):
        return Response({
            'links': {
               'next': self.get_next_link(),
               'previous': self.get_previous_link()
            },
            'count': self.page.paginator.count,
            'results': data
        })

As long as you don't need the pagination, you can setup a custom pagination class which would pack your response in whichever layout you may need:

class CountryListPagination(BasePagination):
    def get_paginated_response(self, data):
        return {
            'version': 5,
            'country_list': data
        }

Then all you need to do is to specify this pagination to your class based view:

class CountryListView(generics.ListAPIView):
    # Endpoint : somedomain/international/
    pagination_class = CountryListPagination

Let me know how is this working for you.

相关阅读:
Top