Pagination#

django-modern-rest supports two main pagination patterns:

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:

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.

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."
    }
  }
}

The async variant is identical, except that it uses await paginator.apage(cursor) instead of paginator.page(cursor).

What happens here:

  1. The query accepts cursor and page_size

  2. The paginator is created over the queryset, ordered by rank and name

  3. .page() (or await .apage()) returns a CursorPage

  4. The page is mapped to the response model CursorPaginated

Client protocol#

  1. The first request is made without the cursor parameter

  2. The response contains next_cursor

  3. To fetch the next page, pass next_cursor back as the cursor parameter

  4. Repeat until next_cursor becomes None

The response shape looks like this:

response.json#
{
    "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 |-| separator

  • The 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:

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.