Django Rest Framework: LimitZeroNoResultsPagination custom pagination

Django Rest Framework: LimitZeroNoResultsPagination custom pagination

A custom pagination to return empty data when limit=0

Django The Right Way's photo
Django The Right Way
ยทMar 12, 2022ยท

2 min read

Subscribe to my newsletter and never miss my upcoming articles

When talking about LimitOffsetPagination in django rest framework, it handles limit as strictly positive integer only (1,2,3,4.......). Whenever you send any non positive numbers/negative numbers including zero (0) to the limit query LimitOffsetPagination will ignore this limit value and will work with it's own customizable default_limit attribute which indeed can be customized using PAGE_SIZE settings for REST_FRAMEWORK

Let's talk about my scenario

Whenever i send limit=0 params for the pagination, it ignores this values and sends/returns me whole lot of data(according to default_limit). I wanted to change this behaviour of the LimitOffsetPagination class so that the pagination class return empty data i.e zero data when i send limit=0 params

so, lets customize the LimitOffsetPagination class

from rest_framework.pagination import LimitOffsetPagination, _positive_int

class LimitZeroNoResultsPagination(LimitOffsetPagination):
    def get_limit(self, request):
        if self.limit_query_param:
                return _positive_int(
            except (KeyError, ValueError):

        return self.default_limit

If, you compare what we customized in this class then you can see we changed strict=False for the _positive_int function

Note: _positive_int is a private function, i do not promote using private func but in this case i needed it so please use this responsibly.

So, when you use this Pagination class for your API's and use limit=0 then you will see this


Where do i use this ?

I use this limit=0 whenever i want extra data from the API like the total count but don't want it's data

Tested on

  • Django(3.0.3) and Django Rest Framework(3.11.0)
  • Django(4.0.2) and Django Rest Framework(3.13.1)