我正在使用Django REST框架和PageNumberPagination类来序列化模型内容。它的输出如下:
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"foo": "foo",
"bar": "bar"
}
}
如何将输出中的results
字段名更改为其他名称?像foo_results
或authors
或我想要的任何内容?
我正在使用通用视图集和序列化程序。
答案 0 :(得分:2)
通过文档custom-pagination-styles,您可以尝试
class CustomPagination(pagination.PageNumberPagination):
def get_paginated_response(self, data):
return Response({
'next': self.get_next_link(),
'previous': self.get_previous_link()
'count': self.page.paginator.count,
'WHATDOYOUWANTHERE': data,
# ^^^^^^^^^^
})
如果你想在paginator的设置更新数据中将其设置为默认值
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'my_project.core.pagination.CustomPagination',
# ^^^ CHANGE PATH TO YOUR PAGINATOR CLASS ^^^
'PAGE_SIZE': 100
}
或通过参数modifying-the-pagination-style
包含到您的视图集中pagination_class = CustomPagination
答案 1 :(得分:1)
官方documentation中有一个例子。
创建一个自定义分页类,如示例所示:
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''foo_results': data
})
在settings.py
中填写以下内容:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'path.to.your.custom.pagination',
'PAGE_SIZE': 100
}