Pagination#
django-modern-rest supports two main pagination patterns:
Limit/offset pagination, based on the built-in
django.core.paginator.PaginatorCursor (also known as keyset or seek) pagination, based on the first-party
CursorPaginator
Use limit/offset for simple and relatively small collections. Use cursor pagination for large tables and for feeds that keep receiving new rows while a client is paging through them.
Limit offset#
We support the built-in django.core.paginator.Paginator.
To do so, we only provide metadata for the default pagination:
1from typing import Final, NotRequired
2
3import pydantic
4from django.core.paginator import Paginator
5from typing_extensions import TypedDict
6
7from dmr import Controller, Query
8from dmr.pagination import Page, Paginated
9from dmr.plugins.pydantic import PydanticFastSerializer
10
11
12class _User(pydantic.BaseModel):
13 email: str
14
15
16class _PageQuery(TypedDict):
17 page_size: NotRequired[int]
18 page: NotRequired[int]
19
20
21_USERS: Final = (
22 _User(email='one@example.com'),
23 _User(email='two@example.com'),
24 _User(email='three@example.com'),
25)
26
27
28class UsersController(Controller[PydanticFastSerializer]):
29 def get(self, parsed_query: Query[_PageQuery]) -> Paginated[_User]:
30 page = parsed_query.get('page', 1)
31 page_size = parsed_query.get('page_size', 2)
32
33 paginator = Paginator(_USERS, page_size)
34 return Paginated(
35 count=paginator.count,
36 num_pages=paginator.num_pages,
37 per_page=paginator.per_page,
38 page=Page(
39 number=page,
40 object_list=list(paginator.page(page).object_list),
41 ),
42 )
43
Run result
$ curl http://127.0.0.1:8000/api/users/ -X GET
{"count":3,"num_pages":2,"per_page":2,"page":{"number":1,"object_list":[{"email":"one@example.com"},{"email":"two@example.com"}]}}
$ curl 'http://127.0.0.1:8000/api/users/?page=2' -X GET
{"count":3,"num_pages":2,"per_page":2,"page":{"number":2,"object_list":[{"email":"three@example.com"}]}}
OpenAPI Schema
Preview openapi.json
{
"components": {
"schemas": {
"ErrorDetail": {
"description": "Base schema for error details description.",
"properties": {
"loc": {
"items": {
"anyOf": [
{
"type": "integer"
},
{
"type": "string"
}
]
},
"title": "Loc",
"type": "array"
},
"msg": {
"title": "Msg",
"type": "string"
},
"type": {
"title": "Type",
"type": "string"
}
},
"required": [
"msg"
],
"title": "ErrorDetail",
"type": "object"
},
"ErrorModel": {
"description": "Default error response schema.\n\nCan be customized.\nSee :ref:`customizing-error-messages` for more details.",
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ErrorDetail"
},
"title": "Detail",
"type": "array"
}
},
"required": [
"detail"
],
"title": "ErrorModel",
"type": "object"
},
"Page__User_": {
"description": "Default page model for serialization.\n\nCan be used when using pagination with ``django-modern-rest``.\n\nAttributes:\n number: Page number. For example: ``5`` page out of ``10`` total pages.\n object_list: Generic sequence of objects on this page.",
"properties": {
"number": {
"title": "Number",
"type": "integer"
},
"object_list": {
"items": {
"$ref": "#/components/schemas/_User"
},
"title": "Object List",
"type": "array"
}
},
"required": [
"number",
"object_list"
],
"title": "Page",
"type": "object"
},
"Paginated": {
"description": "Helper type to serialize the default ``Paginator`` object.\n\nDjango already ships a pagination system, we don't want to replicate it.\nSo, we only provide metadata.\nSee :class:`django.core.paginator.Paginator` for the exact API.\n\nAttributes:\n count: Total count of all objects that we are paginating.\n num_pages: Total number of pages that we got after pagination.\n per_page: Number of objects per one page.\n page: :class:`Page` object that contains paginated objects on this page.",
"properties": {
"count": {
"title": "Count",
"type": "integer"
},
"num_pages": {
"title": "Num Pages",
"type": "integer"
},
"page": {
"$ref": "#/components/schemas/Page__User_"
},
"per_page": {
"title": "Per Page",
"type": "integer"
}
},
"required": [
"count",
"num_pages",
"per_page",
"page"
],
"title": "Paginated",
"type": "object"
},
"_User": {
"properties": {
"email": {
"title": "Email",
"type": "string"
}
},
"required": [
"email"
],
"title": "_User",
"type": "object"
}
}
},
"info": {
"title": "Django Modern Rest",
"version": "0.1.0"
},
"openapi": "3.2.0",
"paths": {
"/api/userscontroller/": {
"get": {
"operationId": "getUsersControllerApiUserscontroller",
"parameters": [
{
"in": "query",
"name": "page_size",
"schema": {
"title": "Page Size",
"type": "integer"
}
},
{
"in": "query",
"name": "page",
"schema": {
"title": "Page",
"type": "integer"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Paginated"
}
}
},
"description": "OK"
},
"400": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorModel"
}
}
},
"description": "Raised when request components cannot be parsed"
},
"406": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorModel"
}
}
},
"description": "Raised when provided `Accept` header cannot be satisfied"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorModel"
}
}
},
"description": "Raised when returned response does not match the response schema"
}
}
}
}
}
}
If you are using a different pagination system, you can define your own metadata / models and use them with our framework.
Cursor#
Cursor pagination works by remembering the position of the last seen row and asking the database for the next batch of rows after that position.
Unlike limit/offset, it does not use OFFSET,
so it stays fast even on very large tables,
and it never skips or duplicates rows
when new data is inserted in the middle of a collection.
The built-in CursorPaginator
works directly with QuerySet
and has both sync and async APIs.
Important
The paginator requires a stable ordering.
Set .order_by() on your queryset
before creating the paginator.
The primary key fields are appended automatically as tiebreakers,
so your order_by fields do not have to be unique.
Model#
It works with any model:
Views#
Here is an example of a list endpoint with cursor pagination:
Important
We can only paginate stably ordered querysets.
1from http import HTTPStatus
2from typing import final
3
4from django.http import HttpResponse
5from typing_extensions import override
6
7from dmr import Controller, Query
8from dmr.endpoint import Endpoint
9from dmr.pagination import CursorPaginated, CursorPaginator
10from dmr.pagination.cursor import InvalidCursorError
11from dmr.plugins.pydantic.serializer import PydanticFastSerializer
12from dmr.serializer import BaseSerializer
13from server.apps.model_cursor.models import Entry
14from server.apps.model_cursor.schema import (
15 CursorQuery,
16 EntryModel,
17)
18
19
20@final
21class EntryController(Controller[PydanticFastSerializer]):
22 """List entries using cursor-based pagination."""
23
24 def get(
25 self,
26 parsed_query: Query[CursorQuery],
27 ) -> CursorPaginated[EntryModel]:
28 paginator = CursorPaginator(
29 Entry.objects.all().order_by(*parsed_query.order_by),
30 per_page=parsed_query.limit,
31 )
32 page = paginator.page(parsed_query.cursor)
33 return CursorPaginated(
34 next_cursor=page.next_cursor,
35 per_page=paginator.per_page,
36 page=[
37 EntryModel.model_validate(entry) for entry in page.objects_list
38 ],
39 )
40
41 @override
42 def handle_error(
43 self,
44 endpoint: Endpoint,
45 controller: Controller[BaseSerializer],
46 exc: Exception,
47 ) -> HttpResponse:
48 if isinstance(exc, InvalidCursorError):
49 return controller.to_error(
50 controller.format_error(str(exc)),
51 status_code=HTTPStatus.BAD_REQUEST,
52 )
53 raise exc from None
54
Run result
$ curl http://127.0.0.1:8000/api/entries/ -X GET
{"next_cursor":"MnwtfGF8LXwy","per_page":2,"page":[{"rank":1,"name":"c"},{"rank":2,"name":"a"}]}
$ curl 'http://127.0.0.1:8000/api/entries/?cursor=MnwtfGF8LXwy' -X GET
{"next_cursor":"NHwtfGJ8LXw0","per_page":2,"page":[{"rank":3,"name":"e"},{"rank":4,"name":"b"}]}
$ curl 'http://127.0.0.1:8000/api/entries/?cursor=INVALID' -D - -X GET
HTTP/1.1 400 Bad Request
date: Tue, 17 Nov 2026 06:14:24 GMT
server: uvicorn
Content-Type: application/json
X-Frame-Options: DENY
Vary: Accept-Language
Content-Language: en
Content-Length: 52
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin
{"detail":[{"msg":"The cursor cannot be decoded!"}]}
OpenAPI Schema
Preview openapi.json
{
"components": {
"schemas": {
"CursorPaginated": {
"description": "Helper for returning cursor paginated response.\n\nAttributes:\n next_cursor: Encoded cursor to request the next page.\n ``None`` when there are no more pages.\n per_page: Number of objects per one page.\n page: Generic sequence of objects on this page.",
"properties": {
"next_cursor": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"title": "Next Cursor"
},
"page": {
"items": {
"$ref": "#/components/schemas/EntryModel"
},
"title": "Page",
"type": "array"
},
"per_page": {
"title": "Per Page",
"type": "integer"
}
},
"required": [
"next_cursor",
"per_page",
"page"
],
"title": "CursorPaginated",
"type": "object"
},
"EntryModel": {
"properties": {
"name": {
"title": "Name",
"type": "string"
},
"rank": {
"title": "Rank",
"type": "integer"
}
},
"required": [
"rank",
"name"
],
"title": "EntryModel",
"type": "object"
},
"ErrorDetail": {
"description": "Base schema for error details description.",
"properties": {
"loc": {
"items": {
"anyOf": [
{
"type": "integer"
},
{
"type": "string"
}
]
},
"title": "Loc",
"type": "array"
},
"msg": {
"title": "Msg",
"type": "string"
},
"type": {
"title": "Type",
"type": "string"
}
},
"required": [
"msg"
],
"title": "ErrorDetail",
"type": "object"
},
"ErrorModel": {
"description": "Default error response schema.\n\nCan be customized.\nSee :ref:`customizing-error-messages` for more details.",
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ErrorDetail"
},
"title": "Detail",
"type": "array"
}
},
"required": [
"detail"
],
"title": "ErrorModel",
"type": "object"
}
}
},
"info": {
"title": "Django Modern Rest",
"version": "0.1.0"
},
"openapi": "3.2.0",
"paths": {
"/api/entrycontroller/": {
"get": {
"operationId": "getEntryControllerApiEntrycontroller",
"parameters": [
{
"in": "query",
"name": "cursor",
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"title": "Cursor"
}
},
{
"in": "query",
"name": "order_by",
"schema": {
"default": [
"rank",
"name"
],
"items": {
"enum": [
"rank",
"-rank",
"name",
"-name",
"created_at",
"-created_at"
],
"type": "string"
},
"minItems": 1,
"title": "Order By",
"type": "array"
}
},
{
"in": "query",
"name": "limit",
"schema": {
"default": 2,
"exclusiveMaximum": 100,
"exclusiveMinimum": 0,
"title": "Limit",
"type": "integer"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/CursorPaginated"
}
}
},
"description": "OK"
},
"400": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorModel"
}
}
},
"description": "Raised when request components cannot be parsed"
},
"406": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorModel"
}
}
},
"description": "Raised when provided `Accept` header cannot be satisfied"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorModel"
}
}
},
"description": "Raised when returned response does not match the response schema"
}
}
},
"summary": "List entries using cursor-based pagination."
}
}
}
1from http import HTTPStatus
2from typing import final
3
4from django.http import HttpResponse
5from typing_extensions import override
6
7from dmr import Controller, Query
8from dmr.endpoint import Endpoint
9from dmr.pagination import CursorPaginated, CursorPaginator
10from dmr.pagination.cursor import InvalidCursorError
11from dmr.plugins.pydantic.serializer import PydanticFastSerializer
12from dmr.serializer import BaseSerializer
13from server.apps.model_cursor.models import Entry
14from server.apps.model_cursor.schema import (
15 CursorQuery,
16 EntryModel,
17)
18
19
20@final
21class EntryAsyncController(Controller[PydanticFastSerializer]):
22 """List entries using cursor-based pagination (async)."""
23
24 async def get(
25 self,
26 parsed_query: Query[CursorQuery],
27 ) -> CursorPaginated[EntryModel]:
28 paginator = CursorPaginator(
29 Entry.objects.all().order_by(*parsed_query.order_by),
30 per_page=parsed_query.limit,
31 )
32 page = await paginator.apage(parsed_query.cursor)
33 return CursorPaginated(
34 next_cursor=page.next_cursor,
35 per_page=paginator.per_page,
36 page=[
37 EntryModel.model_validate(entry) for entry in page.objects_list
38 ],
39 )
40
41 @override
42 async def handle_async_error(
43 self,
44 endpoint: Endpoint,
45 controller: Controller[BaseSerializer],
46 exc: Exception,
47 ) -> HttpResponse:
48 if isinstance(exc, InvalidCursorError):
49 return controller.to_error(
50 controller.format_error(str(exc)),
51 status_code=HTTPStatus.BAD_REQUEST,
52 )
53 raise exc from None
54
Run result
$ curl http://127.0.0.1:8000/api/entries-async/ -X GET
{"next_cursor":"MnwtfGF8LXwy","per_page":2,"page":[{"rank":1,"name":"c"},{"rank":2,"name":"a"}]}
$ curl 'http://127.0.0.1:8000/api/entries-async/?cursor=MnwtfGF8LXwy' -X GET
{"next_cursor":"NHwtfGJ8LXw0","per_page":2,"page":[{"rank":3,"name":"e"},{"rank":4,"name":"b"}]}
$ curl 'http://127.0.0.1:8000/api/entries-async/?cursor=INVALID' -D - -X GET
HTTP/1.1 400 Bad Request
date: Tue, 17 Nov 2026 06:14:25 GMT
server: uvicorn
Content-Type: application/json
X-Frame-Options: DENY
Vary: Accept-Language
Content-Language: en
Content-Length: 52
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin
{"detail":[{"msg":"The cursor cannot be decoded!"}]}
OpenAPI Schema
Preview openapi.json
{
"components": {
"schemas": {
"CursorPaginated": {
"description": "Helper for returning cursor paginated response.\n\nAttributes:\n next_cursor: Encoded cursor to request the next page.\n ``None`` when there are no more pages.\n per_page: Number of objects per one page.\n page: Generic sequence of objects on this page.",
"properties": {
"next_cursor": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"title": "Next Cursor"
},
"page": {
"items": {
"$ref": "#/components/schemas/EntryModel"
},
"title": "Page",
"type": "array"
},
"per_page": {
"title": "Per Page",
"type": "integer"
}
},
"required": [
"next_cursor",
"per_page",
"page"
],
"title": "CursorPaginated",
"type": "object"
},
"EntryModel": {
"properties": {
"name": {
"title": "Name",
"type": "string"
},
"rank": {
"title": "Rank",
"type": "integer"
}
},
"required": [
"rank",
"name"
],
"title": "EntryModel",
"type": "object"
},
"ErrorDetail": {
"description": "Base schema for error details description.",
"properties": {
"loc": {
"items": {
"anyOf": [
{
"type": "integer"
},
{
"type": "string"
}
]
},
"title": "Loc",
"type": "array"
},
"msg": {
"title": "Msg",
"type": "string"
},
"type": {
"title": "Type",
"type": "string"
}
},
"required": [
"msg"
],
"title": "ErrorDetail",
"type": "object"
},
"ErrorModel": {
"description": "Default error response schema.\n\nCan be customized.\nSee :ref:`customizing-error-messages` for more details.",
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ErrorDetail"
},
"title": "Detail",
"type": "array"
}
},
"required": [
"detail"
],
"title": "ErrorModel",
"type": "object"
}
}
},
"info": {
"title": "Django Modern Rest",
"version": "0.1.0"
},
"openapi": "3.2.0",
"paths": {
"/api/entryasynccontroller/": {
"get": {
"operationId": "getEntryAsyncControllerApiEntryasynccontroller",
"parameters": [
{
"in": "query",
"name": "cursor",
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"title": "Cursor"
}
},
{
"in": "query",
"name": "order_by",
"schema": {
"default": [
"rank",
"name"
],
"items": {
"enum": [
"rank",
"-rank",
"name",
"-name",
"created_at",
"-created_at"
],
"type": "string"
},
"minItems": 1,
"title": "Order By",
"type": "array"
}
},
{
"in": "query",
"name": "limit",
"schema": {
"default": 2,
"exclusiveMaximum": 100,
"exclusiveMinimum": 0,
"title": "Limit",
"type": "integer"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/CursorPaginated"
}
}
},
"description": "OK"
},
"400": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorModel"
}
}
},
"description": "Raised when request components cannot be parsed"
},
"406": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorModel"
}
}
},
"description": "Raised when provided `Accept` header cannot be satisfied"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorModel"
}
}
},
"description": "Raised when returned response does not match the response schema"
}
}
},
"summary": "List entries using cursor-based pagination (async)."
}
}
}
The async variant is identical,
except that it uses await paginator.apage(cursor)
instead of paginator.page(cursor).
What happens here:
The query accepts
cursorandpage_sizeThe paginator is created over the queryset, ordered by
rankandname.page()(orawait .apage()) returns aCursorPageThe page is mapped to the response model
CursorPaginated
Client protocol#
The first request is made without the
cursorparameterThe response contains
next_cursorTo fetch the next page, pass
next_cursorback as thecursorparameterRepeat until
next_cursorbecomesNone
The response shape looks like this:
{
"next_cursor": "MnwtfGF8LXwy",
"per_page": 2,
"page": [
{"rank": 1, "name": "c"},
{"rank": 2, "name": "a"}
]
}
Note
next_cursor is null only when the page has fewer items
than per_page.
If the total number of items is an exact multiple of per_page,
one extra request will return an empty page
with next_cursor set to null.
Warning
A cursor is bound to the ordering it was created with.
If you expose a dynamic order_by or filters,
the client must not change them while following a cursor:
the cursor values will be compared against the new ordering,
and the client will silently receive wrong rows.
The request fails with 400 Bad Request
only when the number of ordered fields changes.
How it works#
The cursor is an encoded tuple of the ordered field values of the last row of the previous page
By default it is encoded with
base64.urlsafe_b64encode, so the result only contains URL-safe characters; the values are joined with the|-|separatorThe next page is fetched with a single range query over the ordered fields, a lexicographic comparison of the whole tuple
Because the primary key fields are always appended as tiebreakers, two rows can never share the same cursor position
Unlike many other cursor pagination implementations,
the fields in your order_by do not have to be unique:
it is enough to order by a plain non-unique field
like created_at or rank,
because the primary key fields are appended to the ordering
as tiebreakers automatically.
This works because the range query is not a single comparison,
but a disjunction over the whole ordering tuple.
For a queryset ordered by rank
(with the primary key appended as a tiebreaker),
the paginator builds:
(rank > cursor.rank)
OR (rank = cursor.rank AND pk > cursor.pk)
The first branch matches every row strictly after the cursor position.
The second branch matches rows that share the same rank value,
ordered by the primary key.
Every extra ordering field extends the chain in the same way.
Customizing the cursor format#
You can pass your own cursor_encoder and cursor_decoder
functions, as well as a custom separator.
For example, you can encrypt your cursor values to not expose any details and
prevent people from forging cursor values:
1from typing import ClassVar, Final, final
2
3import pydantic
4from cryptography.fernet import Fernet
5
6from dmr import Controller, Query
7from dmr.pagination import CursorPaginated, CursorPaginator
8from dmr.plugins.pydantic import PydanticFastSerializer
9from server.apps.model_cursor.models import ( # type: ignore[import-not-found, unused-ignore]
10 Entry,
11)
12
13FERNET_ENCODER: Final = Fernet(b'rrCDOaFu3QjLiRa8fwykCVp7nuPcKIbxnhZSiI_thBE=')
14
15
16def custom_encoder(to_encode: str) -> str:
17 """Encode a string using Fernet symmetric encryption."""
18 return FERNET_ENCODER.encrypt(to_encode.encode()).decode(
19 'utf-8',
20 )
21
22
23def custom_decoder(to_decode: str) -> str:
24 """Decode a string using Fernet symmetric encryption."""
25 return FERNET_ENCODER.decrypt(to_decode.encode()).decode(
26 'utf-8',
27 )
28
29
30@final
31class _PageQuery(pydantic.BaseModel):
32 __dmr_cast_null__: ClassVar[frozenset[str]] = frozenset(('cursor',))
33
34 cursor: str | None = None
35
36
37class _EntrySchema(pydantic.BaseModel):
38 rank: int
39 name: str
40
41
42class EntryController(Controller[PydanticFastSerializer]):
43 """List entries using cursor-based pagination."""
44
45 def get(
46 self,
47 parsed_query: Query[_PageQuery],
48 ) -> CursorPaginated[_EntrySchema]:
49 paginator = CursorPaginator(
50 Entry.objects.all().order_by('rank', 'name'),
51 per_page=2,
52 cursor_encoder=custom_encoder,
53 cursor_decoder=custom_decoder,
54 )
55 page = paginator.page(parsed_query.cursor)
56 return CursorPaginated(
57 next_cursor=page.next_cursor,
58 per_page=paginator.per_page,
59 page=[
60 _EntrySchema.model_validate(entry, from_attributes=True)
61 for entry in page.objects_list
62 ],
63 )
64
Run result
$ curl http://127.0.0.1:8000/api/entries/ -X GET
{"next_cursor":"gAAAAABq-_DCqcElL69YELhQxtqFHmQrIZwKXTkHYVkX1hBxGVnHKcu_CN7kAWPNc1eJU-Lq4uovrzRyuXYxeyn8rcOtQTV2ig==","per_page":2,"page":[{"rank":1,"name":"c"},{"rank":2,"name":"a"}]}
Note
By default cursors are encoded with base64.urlsafe_b64encode,
so they only contain URL-safe characters
and can be passed in query strings as-is.
If you switch to a different alphabet,
like plain base64.b64encode with its + and / characters,
they must be percent-encoded by the client.
Errors#
A cursor is a client-provided value.
When it cannot be decoded,
or when it contains a different number of fields than expected,
the paginator raises InvalidCursorError.
Unlike other framework errors,
it is not handled by the default
global_error_handler() on purpose.
You should catch it in your view
and convert it to an error response yourself.
Alternatively, you can handle the error
in handle_error()
or in a custom global error handler,
see Error handling for details.
If your endpoint can return this error,
remember to document the 400 status code
in its ResponseSpec definitions.
Other libraries#
Any other Django-compatible pagination tool should work out of the box. Like django-cursor-pagination or even your custom implementation.
See API reference.