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

03 Giugno 2025 coding # django, python

How to make the paginate decorator optional in Django Ninja

If you're working with Django Ninja and need to retrieve the complete list of elements from a paginated endpoint without creating a separate endpoint, you're in luck.

The @paginate decorator offers more flexibility than you might expect.

Rather than duplicating endpoints, I discovered that creating a custom pagination class allows you to make pagination optional.

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

A thought

What stands out about Django Ninja's pagination design is its emphasis on developer freedom. Even if none of the existing pagination classes meet your specific requirements, the framework provides all the tools necessary to build your own solution.

Links

Vuoi lavorare con me?
Facciamo due chiacchiere.

hi@lucafedrizzi.com

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