Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework: Adding a custom field to a paginated ViewSet

I have a paginated result set so the response comes back like this:

{
"count": 944,
"next": "http://api.visitorlando.teeny/consumer/listings/?page=3",
"previous": "http://api.visitorlando.teeny/consumer/listings/",
"results": [
 {...}]
}

I need to add another custom field to the Response like this:

{
"count": 944,
"custom_field": "test",
"next": "http://api.visitorlando.teeny/consumer/listings/?page=3",
"previous": "http://api.visitorlando.teeny/consumer/listings/",
"results": [
 {...}]
}

and I am inside a ViewSet. How am I able to do this?

like image 491
karmacode Avatar asked Nov 02 '25 04:11

karmacode


1 Answers

You may define your custom paginate class:

class CustomPagination(pagination.PageNumberPagination):
    def get_paginated_response(self, data):
        return Response({
            'links': {
               'next': self.get_next_link(),
               'previous': self.get_previous_link()
            },
            'count': self.page.paginator.count,
            'results': data,
            "custom_field": "test",
        })


class YourListView(generics.ListAPIView):
    pagination_class = CustomPagination

more details: custom-pagination


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!