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和“country_list”:[]}) / p>
我以这种方式设置了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中编码什么来呈现像上面那样的字典?我真的不确定。
答案 0 :(得分: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
答案 1 :(得分:0)
你可以从这里建立这个想法: http://www.django-rest-framework.org/api-guide/pagination/#example
假设我们想要使用修改后的格式替换默认的分页输出样式,该格式包含嵌套链接下的下一个和上一个链接&#39;键。我们可以像这样指定一个自定义分页类:
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
让我知道这对你有用。