1

I have written CustomPagination from drf in a separate file in my project which is like this.

class ProductPageNumberPagination(PageNumberPagination):
    page_size = 1


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
        })

Now I am inheriting it in my view like this:

class CouponView(APIView,CustomPagination):
    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()           
            serializer = CouponSerializer(abc,many=True)
            return Response(serializer.data,status=200)

However, the above code is not working. If I had imported default PageNumberPagination it will work but why inheriting my custom class is not working is my question. Seems like only the default class be inherited and not the custom-defined one.

Reactoo
  • 916
  • 2
  • 12
  • 40

2 Answers2

2

Since you're overriding the get() method, you'll need to perform the paginate_queryset() as well, before you use the serializer:

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

        ...
        else:
            abc = self.paginate_queryset(Coupons.objects.all())
            serializer = CouponSerializer(abc,many=True)
            return Response(serializer.data,status=200)
gabopushups
  • 185
  • 2
  • 11
0

Try to return self.get_paginated_response() instead of Response, like this:

class CouponView(APIView,CustomPagination):
    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 Response(serializer.data, status=200)
        else:
            abc = Coupons.objects.all()           
            serializer = CouponSerializer(abc,many=True)
            return self.get_paginated_response(serializer.data)

And I think it should be returned Response in the if block instead of raw data.

oklymeno
  • 71
  • 4
  • The problem of this solution is that you can't attach other attributes, like you would in `Response`, such as headers or status – gabopushups Nov 09 '22 at 02:07