Is it possible to get how many pages an API request has available? For example, this is my response:
{
"count": 44,
"next": "http://localhost:8000/api/ingested_files/?page=2",
"previous": null,
"results": [
{
"id": 44,
....
I'm pulling 20 elements per page, so there should be 2 pages in total, but currently the way it's set up I can get next and previous, but there's no context as to what the total amount of pages is. Sure I could do some math and get how many possible pages using the count, but I imagine something like this would be native to the framework, no?
This is my view:
class IngestedFileView(generics.ListAPIView):
queryset = IngestedFile.objects.all()
serializer_class = IngestedFileSerializer
This is my serializer:
class IngestedFileSerializer(serializers.ModelSerializer):
class Meta:
model = IngestedFile
fields = ('id', 'filename', 'ingested_date', 'progress', 'processed', 'processed_date', 'error')
REST framework includes support for customizable pagination styles. This allows you to modify how large result sets are split into individual pages of data.
Django provides high-level and low-level ways to help you manage paginated data – that is, data that's split across several pages, with “Previous/Next” links.
Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django.
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:
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