I currently have an API view setup as follows:
class CartView(APIView):
authentication_classes = [SessionAuthentication, TokenAuthentication]
permission_classes = [IsAuthenticated, ]
api_view = ['GET', 'POST']
def get(self, request, format=None):
try:
cart = request.user.cart
except Cart.DoesNotExist:
cart = Cart.objects.create(user=request.user)
cart_details = cart.cart_details.all()
serializer = CartDetailSerializer(cart_details, many=True, fields=['id', 'item', 'quantity', 'product_type'])
return Response(serializer.data)
Here CartDetailSerializer
is a normal ModelSerializer.
I want to paginate this API. However, in the docs of DRF, I found this:
If you're using a regular APIView, you'll need to call into the pagination API yourself to ensure you return a paginated response.
There is no example provided on how to paginate a regular APIView API.
Can anyone post an example which I can use in above scenario.
Thanks.
I am using DRF version 3.6.2. You don't need to code so much. Just use this simple steps.
if you want search functionality by getting method, you can write below code
I prefer extending the Paginator class, here is how it would look:
While the way rayy mentions is a possibility, django-rest-framework can handle this internally with some additional features that make working with your API much easier. (*note django-rest-framework's pagination is built from the Django paginator from django.core.paginator)
Right after what you quoted is the key information to solving this problem:
Slight correction to what is stated there: look at the ListModelMixin.
If you go to these two links you can see the source code for the above files: generics.py mixins.py
What you need to do is include something like the following to get pagination to work in the APIView (**note: this code is untested but the idea is correct. There is also a better way of writing this rather than having to include the code in every view but I will leave that up to you to keep my answer short and understandable):
I hope this was of more help to you and others who come across this post.
When using regular APIView, you need to use Django's own Paginator class.
Django Pagination in Views
In your case you can paginate queryset before sending it to serializer.
Something like this:
Hope this helps.