gor*_*vix 1 django pagination django-rest-framework
假设我有如下视图:
class FooView(ListAPIView):
serializer_class = FooSerializer
pagination_class = FooPagination
Run Code Online (Sandbox Code Playgroud)
它返回一个典型的分页响应,例如:
{
"count":2,
"next":null,
"previous":null,
"results":[
{
"id":1,"name":"Josh"
},
{
"id":2,"name":"Vicky"
}]
}
Run Code Online (Sandbox Code Playgroud)
如何(如果可能)将自定义字段添加到此响应中以使结果如下?
{
"count":2,
"next":null,
"previous":null,
"custom":"some value",
"results":[
{
"id":1,"name":"Josh"
},
{
"id":2,"name":"Vicky"
}]
}
Run Code Online (Sandbox Code Playgroud)
假设“某个值”以适当的方法计算并存储,例如:
def get_queryset(self):
self.custom = get_custom_value(self)
# etc...
Run Code Online (Sandbox Code Playgroud)
另一种可能的解决方案是将自定义字段添加到您的响应中,不需要覆盖 Pagination 类
def list(self, request, *args, **kwargs):
response = super(YourClass, self).list(request, args, kwargs)
# Add data to response.data Example for your object:
response.data['custom_fields'] = 10 # Or wherever you get this values from
return response
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1424 次 |
| 最近记录: |