Why does Django Rest Framework Pagination work with Django.http JsonResonse() and not rest_framework.response Response()
I've followed the tutorial on enabling/creating custom pagination for ModelViewSets in Django Rest Framework (DRF).
But the custom pagination doesn't show up as part of the content of the response. I only get my results split according to the 'PAGE_SIZE'
setting in an object labeled data
with no count, or page_size
as defined in my custom pagination class.
I added the following lines in my setting.py file:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'core.pagination.CustomPagination',
'PAGE_SIZE': 2,
...
}
Custom pagination class:
from rest_framework import pagination
from rest_framework.response import Response
class CustomPagination(pagination.PageNumberPagination):
page_size = 2
def get_paginated_response(self, data):
return JsonResponse({
'page_size': self.page_size,
'count': self.page.paginator.count,
'results': data
})
My ModelViewSet
class PersonViewSet(viewsets.ReadOnlyModelViewSet):
"""
A simple ViewSet for listing or retrieving and creating people.
"""
queryset = Person.objects.all()
permission_classes = (IsAuthenticated,)
serializer_class = PersonSerializer
pagination_class = CustomPagination
I have tried changing the ModelViewSet to various other types such as genericViewSet
and defining my list()
functions etc.
The results from the list API endpoint I expected:
{
"page_size": 2,
"count": 2548,
"results": [
{
"type": "Person"
},
{
"type": "Person"
}
]
}
The results from the list API endpoint I got:
{
"data": [
{
"type": "Person"
}
},
{
"type": "Person"
}
}
]
}
When I tried changing the response type in my CustomPagination
class to JsonResponse
I got the result I expected. Why is this?
Changed CustomPagination
Class:
from rest_framework import pagination
from django.http import JsonResponse
class CustomPagination(pagination.PageNumberPagination):
page_size = 2
def get_paginated_response(self, data):
return JsonResponse({
# 'page': self.page.paginator.page,
'page_size': self.page_size,
'count': self.page.paginator.count,
'results': data
})