0
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)

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

我的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 中编写什么代码来呈现像上面这样的字典?我真的不确定。

4

2 回答 2

0

您可以从这里建立这个想法:http: //www.django-rest-framework.org/api-guide/pagination/#example

假设我们想用修改的格式替换默认的分页输出样式,该格式在嵌套的“链接”键下包含下一个和上一个链接。我们可以像这样指定一个自定义分页类:

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 CountryListPagination(BasePagination):
    def get_paginated_response(self, data):
        return {
            'version': 5,
            'country_list': data
        }

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

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

让我知道这对你有什么作用。

于 2015-10-09T06:24:36.627 回答
0

尝试这个

 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
于 2015-10-09T03:07:42.367 回答