django api framework getting total pages available
You can create your own pagination serializer:
from django.conf import settings
from rest_framework import pagination
from rest_framework.response import Response
class YourPagination(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,
'total_pages': self.page.paginator.num_pages,
'results': data
})
In your configuration in settings.py
you add YourPagination
class as the Default Pagination Class.
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'my_project.apps.pagination.YourPagination',
'PAGE_SIZE': 20
}
References:
- Custom Pagination
You can extend PageNumberPagination class and override get_paginated_response method to get total pages count.
class PageNumberPaginationWithCount(pagination.PageNumberPagination):
def get_paginated_response(self, data):
response = super(PageNumberPaginationWithCount, self).get_paginated_response(data)
response.data['total_pages'] = self.page.paginator.num_pages
return response
And then in settings.py, add PageNumberPaginationWithCount class as the Default Pagination Class.
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'my_project.apps.pagination.PageNumberPaginationWithCount',
'PAGE_SIZE': 30
}