django-rest-framework [Intermediate] Complex Usage Example


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:

  1. On the 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:

        'PAGE_SIZE': 50
  2. Now in our (or in another .py ex:, 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.

  3. In our, 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.