Search code examples
djangoapidjango-rest-frameworkdjango-viewsdjango-pagination

custom pagination not woking in apiview of Django rest


I have a custom pagination class in a separate file and until now I have been importing it in a ListAPIView, but this time I tried with APIView, but it didn't work.

My pagination class:

class CustomPagination(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,
            'page_size' : 15,
            'results': data
        })

I am trying to use custom pagination because I can have the count of the objects as well.

My view where I try to implement the pagination:

from apps.products.api.pagination import CustomPagination

class CouponView(APIView):
    permission_classes = [AllowAny]
    #pagination_class = CustomPagination


    def get(self,request,pk = None,*args,**kwargs):

        id = pk
        if id is not None:
            abc = Coupons.objects.get(id=id)
            serializer = CouponSerializer(abc)
            return serializer.data
        else:
            abc = Coupons.objects.all()
            paginator = CustomPagination()
            result_page = paginator.paginate_queryset(abc, request)
            serializer = CouponSerializer(result_page,many=True)
            return Response (serializer.data,status=status.HTTP_200_OK)

Solution

  • I did the following and it worked:

    def get(self,request,pk = None,*args,**kwargs):
    
            id = pk
            if id is not None:
                abc = Coupons.objects.get(id=id)
                serializer = CouponSerializer(abc)
                return serializer.data
            else:
                abc = Coupons.objects.all()
                paginator = CustomPagination()
                result_page = paginator.paginate_queryset(abc,request)
                serializer = CouponSerializer(result_page,many=True)
                # return Response (serializer.data,status=status.HTTP_200_OK)
                return paginator.get_paginated_response(serializer.data)