假设我有如下视图:
class FooView(ListAPIView):
serializer_class = FooSerializer
pagination_class = FooPagination
返回典型的分页响应,例如:
{
"count":2,
"next":null,
"previous":null,
"results":[
{
"id":1,"name":"Josh"
},
{
"id":2,"name":"Vicky"
}]
}
如何(如果可能)可以将自定义字段添加到此响应中,结果如下所示?
{
"count":2,
"next":null,
"previous":null,
"custom":"some value",
"results":[
{
"id":1,"name":"Josh"
},
{
"id":2,"name":"Vicky"
}]
}
假设"某些价值"以适当的方法计算并存储,例如:
def get_queryset(self):
self.custom = get_custom_value(self)
# etc...
答案 0 :(得分:1)
您需要覆盖get_paginated_response()
课程中的FooPagination
,才能在回复中添加自定义字段。
您可以执行以下操作:
class FooPagination(pagination.PageNumberPagination):
def get_paginated_response(self, data):
return Response(OrderedDict([
('count', self.page.paginator.count),
('next', self.get_next_link()),
('previous', self.get_previous_link()),
('custom': some_value), # add the 'custom' field
('results', data),
]))
答案 1 :(得分:0)
另一种可能的解决方案是在响应中添加自定义字段,不需要覆盖分页类
users.find().skip(50).limit(50)
答案 2 :(得分:0)
在 Rahul Gupta 答案的修改版本中,我们可以更新从 get_paginated_response 函数返回的数据,只需向 OrderedDict 添加一个自定义字段。 这将保持超类方法不变,将来如果超方法发生任何新的变化,它不会影响
class CustomFieldPageNumberPagination(pagination.PageNumberPagination):
def get_paginated_response(self, data):
paginated_response = super(CustomFieldPageNumberPagination, self).get_paginated_response(data=data)
paginated_response.data['custom_field']=<custom_field_value>
return paginated_response