To implement custom pagination logic, subclass ninja.pagination.PaginationBase (or AsyncPaginationBase for async support) and implement the following:
Input(Schema): A nested class defining the query parameters the paginator accepts.Output(Schema): A nested class defining the structure of the paginated response.paginate_queryset(self, queryset, pagination, **params): The method that performs the slicing/logic. It receives the queryset, the validated pagination input, and **params (which includes the request object).
Note on Output Attributes: By default, items are placed in an 'items' key in the response. To change this, set the items_attribute string attribute on your class.
from ninja.pagination import paginate, PaginationBase
from ninja import Schema
from typing import List, Any
class CustomPagination(PaginationBase):
class Input(Schema):
skip: int
class Output(Schema):
items: List[Any]
total: int
per_page: int
# Change the key in the JSON response from 'items' to 'results'
items_attribute: str = "items"
def paginate_queryset(self, queryset, pagination: Input, **params):
skip = pagination.skip
return {
'items': queryset[skip : skip + 5],
'total': queryset.count(),
'per_page': 5,
}
@api.get('/users', response=List[UserSchema])
@paginate(CustomPagination)
def list_users(request):
return User.objects.all()