~ / Home / Blog / How to make the paginate decorator optional in Django Ninja

03 Giugno 2025 • # django, python

How to make the paginate decorator optional in Django Ninja

I needed to reuse an endpoint, but it was paginated. To make pagination optional, I found that the best approach is to create a custom pagination class.

The snippets

from ninja.pagination import LimitOffsetPagination


class OptionalLimitOffsetPagination(LimitOffsetPagination):
	def paginate_queryset(self, queryset, pagination, **params):
		# Get `unlimited` from the params.
		unlimited = params.get("unlimited", None)

		# Return all the values.
		if unlimited:
			return {
					"items": queryset,
					"count": queryset.count(),
			}

		# Otherwise, apply normal pagination.
		return super().paginate_queryset(queryset, pagination, **params)

As the last step, you have to add unlimited as a parameter to your endpoint.

@paginate(OptionalLimitOffsetPagination)
def my_endpoint(request, unlimited: bool = False):
	pass

It is immediately noticeable that this pagination design intends to give maximum freedom. Even if there isn't already a class suitable for your needs, you have everything you need to create it.

Links

Vuoi lavorare con me?
Facciamo due chiacchiere.

hi@lucafedrizzi.com

░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░