Prologue:
I have seen this question arising in more than one posts:
- Django Rest Framework - APIView Pagination
- Pagination not working in DRF APIView
- Django rest framework global pagination parameters not working for ModelViewSet
and can also be applied here:
I have composed an example on SO Documentation to unify my answers in the above questions but since the Documentation will get shutdown on August 8 2017, I will follow the suggestion of this widely upvoted and discussed meta answer and transform my example to a self-answered post.
Of course I would be more than happy to see any different approach as well!!
Question:
I want to use a Non Generic View/Viewset (eg: APIView
) on a Django Rest Framework project.
As I read on the pagination documentation:
Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular
APIView
, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for themixins.ListModelMixin
andgenerics.GenericAPIView
classes for an example.
Can I still continue using a non generic view/viewset?
How can I implement pagination on it?
We can find a solution without the need to reinvent the wheel:
Let's have a look on how the
generics
pagination is implemented: django-rest-framework/rest_framework/generics.py.That is exactly what we are going to use to our view as well!
Let's assume that we have a global pagination setup like the following in:
settings.py
:In order not to bloat our view/viewset's code, we can create a custom mixin to store our pagination code:
Then on
views.py
:And now we have an
APIView
with pagination.