Django Rest Framework: LimitZeroNoResultsPagination custom pagination
A custom pagination to return empty data when limit=0

Search for a command to run...
A custom pagination to return empty data when limit=0

No comments yet. Be the first to comment.
Nothing serious, just experimenting on Django Framework

Working with simple media uploads and serving these media files

Using static files like JavaScript, CSS, images with Django

Class() based views in Django

function() based views in Django

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
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
LimitOffsetPagination classfrom rest_framework.pagination import LimitOffsetPagination, _positive_int
class LimitZeroNoResultsPagination(LimitOffsetPagination):
def get_limit(self, request):
if self.limit_query_param:
try:
return _positive_int(
request.query_params[self.limit_query_param],
strict=False,
cutoff=self.max_limit
)
except (KeyError, ValueError):
pass
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

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