我正在使用 django-rest-framework 来退回订单。订单使用默认的 JSONRenderer 类呈现。现在,它们以这种形式返回:
{
"count": 50,
"next": "http://127.0.0.1:8000/api/sales/?_=1444830088899&page=2",
"previous": null,
"results": [
{
"order_number": 20,
"customer_number": 100
},
{
"order_number": 21,
"customer_number": 101
}
]
}
我希望 django-rest-framework 像这样渲染它:
{
"count": 50,
"next": "http://127.0.0.1:8000/api/sales/?_=1444830088899&page=2",
"previous": null,
"results": {
"20": {
"customer_number": 100
},
"21": {
"customer_number": 101
}
}
}
View :
class SalesList(generics.ListCreateAPIView):
serializer_class = SalesSerializer
def get_queryset(self):
return get_sales(self.request, None)
有办法做到这一点吗?
最佳答案
这是 PageNumberPagination
分页类使用的默认分页样式。要更改此分页样式并在 results
键中返回自定义响应,我们需要 implement a custom pagination style它将从 PageNumberPagination
扩展。
在 CustomPagination
类中,我们将重写 get_pagination_response()
并指定自定义分页输出样式。
from rest_framework.compat import OrderedDict
class CustomPagination(pagination.PageNumberPagination):
def get_paginated_response(self, data):
# prepare the custom results using 'data'
custom_results = {x['order_number']:{'customer_number': x['customer_number']} for x in data}
return Response(OrderedDict([
('count', self.page.paginator.count),
('next', self.get_next_link()),
('previous', self.get_previous_link()),
('results', custom_results) # specify the custom results dictionary
]))
然后我们需要在 DRF 设置中指定此自定义分页类。
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'my_project.my_app.pagination.CustomPagination', # specify the custom pagination class
...
}
关于json - 为 django-rest-framework 中的每个序列化元素添加对象键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33129553/