Pagination in DRF using APIView
Impement pagination in django using drf and APIView
Pagination helps to retrieve the data from the database as a limited record per page. Often pagination is implemented using the generics views.
APIView in DRF is one of the simplest ways to implement API’s with all CRUD operations in a single view. But when comes to pagination it doesn't provide the same as Generic views.
Often we require pagination in only get methods of API and none of the others don't require them. Here is the entire clear-cut representation with code that helps to implement pagination in APIView.
Settings.py file:
page size can be 100 or 200 or any number, which are records you want to be displayed per page
Code for settings.py:
REST_FRAMEWORK = {
‘DEFAULT_PAGINATION_CLASS’: ‘rest_framework.pagination.PageNumberPagination’,
‘PAGE_SIZE’: 2,
}
Views.py file:
Next, we have to do following imports in Views.py file:
from rest_framework.pagination import PageNumberPagination
Code:
Class view_name(APIView,PageNumberPagination):
serializer_class = Serializer
def get(self,request):
entity =Modelname.objects.all()
results = self.paginate_queryset(entity, request, view=self)
serializer = ModelSerializer(results, many=True)
return self.get_paginated_response(serializer.data)
Urls.py
After that runserver using the command:
Command: python manage.py runserver
Result Preview: