django rest框架中ListApiView的结果如下:
{
"count": 1023
"next": "https://api.example.org/accounts/?page=5",
"previous": "https://api.example.org/accounts/?page=3",
"results": [
…
]
}
如何在JSON结果的根目录中而不是在结果列表中添加自定义字段?
{
"my_custom_field": ...
"count": 1023
"next": "https://api.example.org/accounts/?page=5",
"previous": "https://api.example.org/accounts/?page=3",
"results": [
…
]
}
答案 0 :(得分:1)
您需要修改pagination_class
。创建一个新的分页类并根据需要覆盖get_paginated_response
方法。
class Pagination(PageNumberPagination):
def get_paginated_response(self, data):
return Response({
'my_custom_field': ....,
'next': self.get_next_link(),
'previous': self.get_previous_link(),
'count': self.page.paginator.count,
'results': data
})
class SomeViewSet(ModelViewSet):
pagination_class = Pagination
...
在Pagination
类中,观察get_paginated_response
,您可以在那里拥有自己的字段。