【问题标题】:Django Rest Framework - Customize LimitOffsetPaginationDjango Rest 框架 - 自定义 LimitOffsetPagination
【发布时间】:2019-12-17 23:04:10
【问题描述】:

我尝试在我的 Django Rest 框架中包含分页以限制查询提供的输出数量。为此,我使用了LimitOffsetPagination。 这是我的输出:

{
    "count": 59,
    "next": "http://127.0.0.1:8000/contacts/getContacts/?limit=3&offset=3",
    "previous": null,
    "results": [
        {
            "id": 1,
            "contactName": "Mr.Important"
        },
        {
            "id": 2,
            "contactName": "Mrs.VeryImportant"
        },
        {
            "id": 3,
            "contactName": "Mr.NotSoImportant"
        }
    ]
}

我的问题是:是否可以自定义输出以使nextprevious 链接出现在results JSON 对象中? 我想要的是这样的:

{
    "count": 59,
    "next": "http://127.0.0.1:8000/contacts/getContacts/?limit=3&offset=3",
    "previous": null,
    "results": [
        {
            "id": 1,
            "contactName": "Mr.Important",
            "next": "http://127.0.0.1:8000/contacts/getContacts/?limit=3&offset=3",
            "previous": null,
        },
        {
            "id": 2,
            "contactName": "Mrs.VeryImportant"
            "next": "http://127.0.0.1:8000/contacts/getContacts/?limit=3&offset=3",
            "previous": null,
        },
        {
            "id": 3,
            "contactName": "Mr.NotSoImportant",
            "next": "http://127.0.0.1:8000/contacts/getContacts/?limit=3&offset=3",
            "previous": null,
        }
    ]
}

【问题讨论】:

标签: python django django-rest-framework pagination


【解决方案1】:

分页类在这里无能为力,因为它们旨在获取 N 个项目并通过对输入进行切片返回一些项目 em>.

这里的需求是一种响应改变,所以我们重写了视图类的dispatch()--DRF doc方法.

class MyView(...):
    def alter_response_data(self, _json_response):
        json_response = _json_response.copy()
        results = []
        next_ = json_response['next']
        previous_ = json_response['previous']

        for item in json_response['results']:
            item.update({'next': next_, 'previous': previous_})
            results.append(item)
        json_response['results'] = results
        return json_response

    def dispatch(self, request, *args, **kwargs):
        http_response = super().dispatch(request, *args, **kwargs)
        json_response = http_response.data

        if 'next' in json_response and 'previous' in json_response:
            http_response.data = self.alter_response_data(json_response)

        return http_response

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 2021-01-30
    • 2020-09-22
    相关资源
    最近更新 更多