Django Rest Framework - 封装分页响应
Django Rest Framework - Envelope a Paginated Response
我想将分页回复包装在信封中。结果应如下所示。
{
"data": ["datum 1", "datum 2", "datum 3"],
"meta": {
"some": "meta",
"data": "foo",
},
"page": {
"total": 12345,
"count": 3,
"from": 3,
"to": 6,
"next": "http://example.com?page=2",
"prev": "http://example.com?page=0",
}
}
自定义页面格式可以通过继承PageNumberPagination来实现。
我的问题是关于传递元数据。除了某种形式的带内信号外,我看不出有任何方法可以将它传递给分页。有干净的(呃)方法来做到这一点吗?
class CustomPagination(pagination.PageNumberPagination):
<b>view = None</b>
def paginate_queryset(self, queryset, request, view=None):
<b>self.view = view</b>
return super().paginate_queryset(queryset, request, view)
<b>def get_meta(self, data=None, **meta):
return {
'data_from_view': self.view.__class__.__name__,
'static_data': settings.ROOT_URLCONF,
'len_per_page': len(data),
'dynamic_data_on_thy_fly': meta
}</b>
def get_paginated_response(self, data, **meta):
return Response({
'links': {
'next': self.get_next_link(),
'previous': self.get_previous_link()
},
<b>'meta': self.get_meta(data, **meta),</b>
'count': self.page.paginator.count,
'results': data
})
我想将分页回复包装在信封中。结果应如下所示。
{
"data": ["datum 1", "datum 2", "datum 3"],
"meta": {
"some": "meta",
"data": "foo",
},
"page": {
"total": 12345,
"count": 3,
"from": 3,
"to": 6,
"next": "http://example.com?page=2",
"prev": "http://example.com?page=0",
}
}
自定义页面格式可以通过继承PageNumberPagination来实现。 我的问题是关于传递元数据。除了某种形式的带内信号外,我看不出有任何方法可以将它传递给分页。有干净的(呃)方法来做到这一点吗?
class CustomPagination(pagination.PageNumberPagination):
<b>view = None</b>
def paginate_queryset(self, queryset, request, view=None):
<b>self.view = view</b>
return super().paginate_queryset(queryset, request, view)
<b>def get_meta(self, data=None, **meta):
return {
'data_from_view': self.view.__class__.__name__,
'static_data': settings.ROOT_URLCONF,
'len_per_page': len(data),
'dynamic_data_on_thy_fly': meta
}</b>
def get_paginated_response(self, data, **meta):
return Response({
'links': {
'next': self.get_next_link(),
'previous': self.get_previous_link()
},
<b>'meta': self.get_meta(data, **meta),</b>
'count': self.page.paginator.count,
'results': data
})