所以我有一个分页的结果列表。以下是DRF默认格式化的方式:
{
"count": 1023
"next": "https://api.example.org/accounts/?page=5",
"previous": "https://api.example.org/accounts/?page=3",
"results": [
…
]
}
如何将所有元数据包装到“meta”属性中,以使响应如下所示:
{
"meta": {
"count": 1023
"next": "https://api.example.org/accounts/?page=5",
"previous": "https://api.example.org/accounts/?page=3",
},
"results": [
…
]
}
编辑:感谢Alasdair的回答。我是这样做的:
from rest_framework import pagination
from rest_framework.response import Response
class CustomPagination(pagination.LimitOffsetPagination):
def get_paginated_response(self, data):
return Response({
'meta': {
'next': self.get_next_link(),
'previous': self.get_previous_link(),
'count': self.count
},
'results': data
})
答案 0 :(得分:2)
您需要implement a custom pagination style将所有元数据包装到元属性中。
步骤1实施自定义分页类:
首先,我们将实现一个自定义的分页类WrappedMetadataPagination
,它将继承自pagination.LimitOffsetPagination
。在那里,我们将覆盖get_paginated_response()
并指定我们的自定义分页输出样式。
class WrappedMetadataPagination(pagination.LimitOffsetPagination):
"""
This custom pagination class wraps the metadata about the results
like 'next', 'previous' and 'next' keys into a dictionary with key as 'meta'.
"""
def get_paginated_response(self, data):
return Response({
'meta': { # wrap other keys as dictionary into 'meta' key
'next': self.get_next_link(),
'previous': self.get_previous_link(),
'count': self.count
},
'results': data
})
步骤2在DRF设置中设置自定义类:
实现自定义类后,您需要在DRF设置中指定此自定义分页类。
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'my_project.my_app.pagination.WrappedMetadataPagination', # specify the custom pagination class
...
}