0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.