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.
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With