aminakoy
aminakoy

Reputation: 423

Django Rest Framework - Customize LimitOffsetPagination

I tried to include Pagination in my Django Rest Framework to limit the number of outputs the query provides. For that I used LimitOffsetPagination. Here is my output:

{
    "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"
        }
    ]
}

My question is: Is it possible to customize the output so that the next & previous links appear within the results JSON object? What I want is something like :

{
    "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,
        }
    ]
}

Upvotes: 0

Views: 442

Answers (1)

JPG
JPG

Reputation: 88499

Pagination classes are helpless here because they are meant to take N-number of items and returning a few items by slicing the inputs.

Here, the requirement is a kind of response alteration, so we override the dispatch()--DRF doc method of the view class.

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

Upvotes: 1

Related Questions