lodo_dev
lodo_dev

Reputation: 23

Pagination in Django-Rest-Framework with API-View

It is necessary to display the configured 10 records per swagger page (book api).

The BookListView class in views.py looks like this:

class BookListView(APIView):
  def get(self, request):
   author = set([item.get('ID') for item in Author.objects.values('ID').all()])
   saler = set([item.get('name') for item in Saler.objects.values('name').all()])
    if author:
      salers = Saler.objects.filter(name__in=list(saler - author))
    else:
      salers = Saler.objects.all()
    serializer = SalerListSerializer(salers, many = True)
    return Response(serializer.data)

Now all records are displayed at once, I would like to add pangination and display 10 records on one page.

I added 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.DESIRED_PAGINATION_STYLE', 'PAGE_SIZE': 100 to the settings.py file, but since I am using APIView, this does not work.

What is the way to implement the idea?

Upvotes: 0

Views: 1055

Answers (1)

E. Ferreira
E. Ferreira

Reputation: 159

You need to call your paginator's paginate_queryset method. Since you're using a APIView, it does not have many of the built-in functions to do this for you, but the process is as follows:

  1. Instantiate a paginator:
from rest_framework.settings import api_settings

pagination_class = api_settings.DEFAULT_PAGINATION_CLASS
paginator = pagination_class()
  1. Get a page from your queryset and serialize it:
page = paginator.paginate_queryset(queryset, request, view=self)
serializer = self.get_serializer(page, many=True)
  1. Return a paginated response:
return paginator.get_paginated_response(serializer.data)

This is how django-rest does it with its ListAPIView class. You can go though the code easily by checking out the ListAPIView's list method here.

However, I suggest using a ListAPIView instead of an APIView since it already handles pagination for you.

Upvotes: 1

Related Questions