json - 为 django-rest-framework 中的每个序列化元素添加对象键

标签 json django django-rest-framework

我正在使用 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/

相关文章:

android - JSON 解析器性能低下

python - 当用户注销 Django 时如何删除 session ?

python - View 中的 Django api 调用无法保存外键 userId

json - 如何使用 Swift Object Mapper 映射嵌套对象数组?

json - Powershell 脚本 - Azure sql db - json 文件

python - 如果我要创建联系表单,是否需要在 models.py 中执行某些操作?

python - 无法导入名称 SIGNATURE_HMAC

javascript - Chrome 正在缓存 API 响应而 Safari 没有

javascript - 无法从 Django 获取 POST 数据(从 React 发送)

javascript - 使用 Dustjs 遍历对象数组