Reputation: 1042
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.
Upvotes: 1
Views: 3155
Reputation: 315
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)
Upvotes: 2
Reputation: 71
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.
Upvotes: 0