Lets assume that we have a complex api, with many generic views and some generic viewsets. We want to enable PageNumberPagination
to every view, except one (either generic view or viewset, does not make a difference) for which we want a customized case of LimitOffsetPagination
.
To achieve that we need to:
On the settings.py
we will place our default pagination in order to enable it for every generic view/viewset and we will set PAGE_SIZE
to 50 items:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS':
'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 50
}
Now in our views.py
(or in another .py
ex: paginations.py
), we need to override the LimitOffsetPagination
:
from rest_framework.pagination import LimitOffsetPagination
class MyOffsetPagination(LimitOffsetPagination):
default_limit = 20
max_limit = 1000
A custom LimitOffsetPagination
with PAGE_ZISE
of 20 items and maximum limit
of 1000 items.
In our views.py
, we need to define the pagination_class
of our special view:
imports ...
# ===================================
# PageNumberPagination classes
# ===================================
class FirstView(generics.ListAPIView):
...
class FirstViewSet(viewsets.GenericViewSet):
...
...
# ===================================
# Our custom Pagination class
# ===================================
class IAmSpecialView(generics.ListAPIView):
pagination_class = MyOffsetPagination
...
Now every generic view/viewset in the app has PageNumberPagination
, except IAmSpecial
class, which is indeed special and has its own customized LimitOffsetPagination
.