Teresa Siegmantel
Teresa Siegmantel

Reputation: 903

Django Rest Framework - Envelope a Paginated Response

I want to wrap an paginated response in an envelope. The Result should look like this.

{
    "data": ["datum 1", "datum 2", "datum 3"],
    "meta": {
        "some": "meta",
        "data": "foo",
    },
    "page": {
        "total": 12345,
        "count": 3,
        "from": 3,
        "to": 6,
        "next": "http://example.com?page=2",
        "prev": "http://example.com?page=0",
    }
}

The custom page format can be achieved by inheriting from PageNumberPagination. My question is about passing the Metadata. I do not see any way to pass it to the Pagination except some form of in band signaling. Is there a clean(er) way to do this?

Upvotes: 0

Views: 264

Answers (1)

JPG
JPG

Reputation: 88639

class CustomPagination(pagination.PageNumberPagination):
    view = None

    def paginate_queryset(self, queryset, request, view=None):
        self.view = view
        return super().paginate_queryset(queryset, request, view)

    def get_meta(self, data=None, **meta):
        return {
            'data_from_view': self.view.__class__.__name__,
            'static_data': settings.ROOT_URLCONF,
            'len_per_page': len(data),
            'dynamic_data_on_thy_fly': meta
        }

    def get_paginated_response(self, data, **meta):
        return Response({
            'links': {
                'next': self.get_next_link(),
                'previous': self.get_previous_link()
            },
            'meta': self.get_meta(data, **meta),
            'count': self.page.paginator.count,
            'results': data
        })

Upvotes: 1

Related Questions