django-rest-framework Pagination [Intermediate] Complex Usage Example

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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 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
    }
    
  2. 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.

  3. 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.



Got any django-rest-framework Question?