Sunday, July 31, 2022

[FIXED] How to Make use of Pagination in this API using Django

Issue

Here I am trying to create a getData API using Django Rest Framework in which i want to get data using Pagination, i had created this statically but it should be like (getting PAGE and number of ROWS on that page) in request and accordingly data get fetch from database and also show the number entries i got.

please help me out to solve this, i have no idea about how pagination works logically just have basic understanding.

class DeviceControlPolicyView(APIView):
    def get(self, request):
        if request.data.get('page', 'rows'):
            if request.data.get('page') == "1" and request.data.get('rows') == "1":
                 print(request.data.get('rows'))
                 print(request.data.get('page'))
                 qry = DeviceControlPolicy.objects.all()[0:1]
                 serializer = DeviceControlPolicySerializer(qry, many=True).data
                 entries = 1
                 data = {
                      'details':serializer,
                      'entry':entries
                 }
                 return Response(data)
        elif request.data.get('page') == "1" and request.data.get('rows') == "2":
            print(request.data.get('rows'))
            print(request.data.get('page'))
            qry = DeviceControlPolicy.objects.all()[0:2]
            serializer = DeviceControlPolicySerializer(qry, many=True).data
            entries = 2
            data = {
                'details': serializer,
                'entry': entries
            }
            return Response(data)

Solution

Have a look at DRF's pagination documentation here.

You can set the pagination class in the APIView and have DRF take care of paginating responses from the queryset.

In your case try

from rest_framework import generics
from rest_framework.pagination import PageNumberPagination

class CustomPageNumberPagination(PageNumberPagination):
    page_size = 100
    page_size_query_param = 'rows'
    max_page_size = 1000

class DeviceControlPolicyView(generics.ListAPIView):
    queryset = DeviceControlPolicy.objects.all()
    serializer_class = DeviceControlPolicySerializer
    pagination_class = CustomPageNumberPagination

also refer DRF generics



Answered By - Adithya
Answer Checked By - Senaida (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.