Django Rest Framework 通过 Views.py 显示序列化数据

Django Rest Framework Displaying Serialized data through Views.py

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)

我有一个这样设置的序列化器,我希望显示 serialized.data(这将是一个像这样的字典:{ "version": xx, and "country_list": [ ] } ) 使用 views.py

我的 views.py 设置是这样的:

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

    ## want to display a dictionary like the one below

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

    }

我要在此 CountryListView 中编写什么代码来呈现像上面那样的字典?我真的不确定。

试试这个

 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

您可以从这里借鉴这个想法: 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
        })

只要您不需要分页,就可以设置自定义分页 class,它将您的响应打包成您可能需要的任何布局:

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

然后您需要做的就是将此分页指定到您的 class 基于视图:

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

让我知道这对你有用吗。