Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the 'results' fieldname in Django REST Framework to something else?

I am using Django REST framework, and PageNumberPagination class for serializing the model contents. It outputs as follows:

{
"count": 1,
"next": null,
"previous": null,
"results": [
    {
        "id": 1,
        "foo": "foo",
        "bar": "bar"
    }
}

How do I change the results fieldname in the output to something else? Like foo_results or authors or whatever I want?

I am using generic viewsets and serializers.

like image 377
T-101 Avatar asked Jan 29 '23 06:01

T-101


2 Answers

by docs custom-pagination-styles you can try

class CustomPagination(pagination.PageNumberPagination):

    def get_paginated_response(self, data):

        return Response({
            'next': self.get_next_link(),
            'previous': self.get_previous_link()
            'count': self.page.paginator.count,
            'WHATDOYOUWANTHERE': data,
            # ^^^^^^^^^^
        })

and if you want set it as default in the settings update data for paginator

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'my_project.core.pagination.CustomPagination',
     #                      ^^^ CHANGE PATH TO YOUR PAGINATOR CLASS ^^^
    'PAGE_SIZE': 100
}

or include to your viewset by parameter modifying-the-pagination-style

pagination_class = CustomPagination
like image 127
Brown Bear Avatar answered May 14 '23 05:05

Brown Bear


There is an example in the official documentation.

Create a custom pagination class like in the example:

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''foo_results': data
        })

In your settings.py put the following:

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'path.to.your.custom.pagination',
    'PAGE_SIZE': 100
}
like image 44
cezar Avatar answered May 14 '23 03:05

cezar