Django Django

What does Django's `Paginator` do to your queryset?

Dima Noi 15, 2026

Short Answer

It slices it. Paginator(queryset, per_page) does not fetch anything on construction; asking for a page slices the queryset, which the ORM compiles into LIMIT and OFFSET, so only that page's rows leave the database. One page costs two queries: a COUNT(*) to work out how many pages exist, and the slice itself. The queryset must be ordered, because LIMIT/OFFSET without an ORDER BY lets the database return rows in any order it likes and pages may then overlap or skip rows. The offset grows with the page number, which is what makes deep pages slow on large tables.


How It Works

Paginator is built on queryset slicing, and queryset slicing is lazy. Shipment.objects.all()[10:20] does not fetch twenty rows and discard ten — it sets limits on the underlying query, and the SQL that eventually runs carries LIMIT 10 OFFSET 10. Paginator computes those bounds from the page number and per_page, so page(2) with ten per page slices [10:20].

The count is the other half. To report num_pages, to know whether a next page exists, and to reject out-of-range requests, the paginator needs the total row count, and that is a separate SELECT COUNT(*) against the same filters. It is a cached property, so one Paginator instance counts once however many pages you take from it — but a fresh instance per request, which is the normal pattern, counts once per request.

Ordering is not optional in practice. LIMIT/OFFSET mean "skip n rows, then take m" of whatever order the database chose, and that order is not guaranteed to be stable between two queries. Two requests can therefore return overlapping or missing rows even with no writes in between. Django raises UnorderedObjectListWarning when it notices, and the fix is always an order_by that is deterministic — usually including the primary key to break ties.

The last property is the one that decides architecture. OFFSET n does not let the database jump to row n; it walks and discards n rows first. Page 2 of a small list is free, page 5,000 of a large one reads and throws away 50,000 rows on every request. Keyset pagination avoids this by remembering the last value seen and filtering on it — WHERE reference > 'SHP-0020' ORDER BY reference LIMIT 10 — which an index can seek to directly. The trade is that you can move forwards and backwards but cannot jump to an arbitrary page number, because there is no offset to compute.


Seeing It Run

These steps share a fixture. Create depot/models.py and bootstrap.py as shown in the first step, plus an empty depot/__init__.py, then replace main.py for each later step. Run with:

python3 main.py

One page, two queries

Twenty-five shipments, ten to a page, asking for the second page.

# depot/models.py
from django.db import models


class Shipment(models.Model):
    reference = models.CharField(max_length=20)


# bootstrap.py
import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    INSTALLED_APPS=["depot"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
    DEFAULT_AUTO_FIELD="django.db.models.AutoField",
    USE_TZ=False,
)
django.setup()

from django.db import connection

from depot.models import Shipment


def seed(total=25):
    with connection.schema_editor() as editor:
        editor.create_model(Shipment)
    Shipment.objects.bulk_create(
        [Shipment(reference=f"SHP-{n:04d}") for n in range(1, total + 1)]
    )
    connection.queries_log.clear()


# main.py
from bootstrap import Shipment, connection, seed
from django.core.paginator import Paginator

seed()

paginator = Paginator(Shipment.objects.order_by("reference"), 10)
page = paginator.page(2)
references = [shipment.reference for shipment in page.object_list]

print("page 2 holds:", references[0], "...", references[-1])
print("total rows  :", paginator.count, "over", paginator.num_pages, "pages")
print("queries for that page:", len(connection.queries))
for query in connection.queries:
    print("  ", query["sql"])


page 2 holds: SHP-0011 ... SHP-0020
total rows  : 25 over 3 pages
queries for that page: 2
   SELECT COUNT(*) AS "__count" FROM "depot_shipment"
   SELECT "depot_shipment"."id", "depot_shipment"."reference" FROM "depot_shipment" ORDER BY "depot_shipment"."reference" ASC LIMIT 10 OFFSET 10


Ten rows crossed the wire, not twenty-five. The COUNT(*) came first because num_pages and the range check need a total, and the slice followed as LIMIT 10 OFFSET 10 — exactly the bounds for page 2. Both queries carry the same filters, so a heavily filtered list pays for that filter twice. This is the whole cost model of a page: one count, one slice.

Try it: Change the page size from 10 to 7 and predict three things: which references page 2 holds, how many pages there are, and what the end of the second SQL statement looks like. The result is SHP-0008 ... SHP-0014, 25 over 4 pages and LIMIT 7 OFFSET 7. OFFSET is (page - 1) × size, computed in Python; the database has no idea what a page is, it only receives the two numbers.


Ordering is required, and bad page numbers have two behaviours

Replace main.py. What Django does when the queryset has no ordering, and when the requested page does not exist.

# main.py
import warnings

from bootstrap import Shipment, seed
from django.core.paginator import EmptyPage, Paginator

seed()

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    Paginator(Shipment.objects.all(), 10).page(1).object_list
    print("unordered queryset ->", caught[0].category.__name__)

ordered = Paginator(Shipment.objects.order_by("reference"), 10)
try:
    ordered.page(99)
except EmptyPage as exc:
    print("page(99)           ->", type(exc).__name__+":", exc)

print("get_page(99)       -> page", ordered.get_page(99).number)
print("get_page('x')      -> page", ordered.get_page("x").number)


unordered queryset -> UnorderedObjectListWarning
page(99)           -> EmptyPage: That page contains no results
get_page(99)       -> page 3
get_page('x')      -> page 1


The warning is Django noticing that LIMIT/OFFSET over an unordered queryset cannot promise stable pages — a real defect, not a style complaint, since the same page number can return different rows on two requests. The two accessors then differ deliberately: page() raises EmptyPage and PageNotAnInteger so you can decide what a bad request means, while get_page() clamps out-of-range numbers to the last page and non-numeric input to page 1. get_page() is what a view wants when the page number arrives from a query string.

Try it: Add print("get_page(0) -> page", ordered.get_page(0).number). Zero is a valid integer but not a page number; do you expect page 1 or the last one? You get page 3. get_page() treats two errors differently: something that is not a number ('x') falls back to the first page, and a number outside the range, in either direction, falls back to the last.


The offset grows with the page number

Replace main.py. The SQL tail for three consecutive pages, then the same window fetched by filtering instead.

# main.py
from bootstrap import Shipment, connection, seed
from django.core.paginator import Paginator

seed()

paginator = Paginator(Shipment.objects.order_by("reference"), 10)
for number in (1, 2, 3):
    connection.queries_log.clear()
    list(paginator.page(number).object_list)
    tail = connection.queries[-1]["sql"].split("ORDER BY", 1)[1].strip()
    print(f"page {number}:", tail)

connection.queries_log.clear()
after = Shipment.objects.filter(reference__gt="SHP-0020").order_by("reference")[:10]
rows = [shipment.reference for shipment in after]
tail = connection.queries[-1]["sql"].split("WHERE", 1)[1].strip()
print("keyset:", tail)
print("        returned", rows[0], "...", rows[-1])


page 1: "depot_shipment"."reference" ASC LIMIT 10
page 2: "depot_shipment"."reference" ASC LIMIT 10 OFFSET 10
page 3: "depot_shipment"."reference" ASC LIMIT 5 OFFSET 20
keyset: "depot_shipment"."reference" > 'SHP-0020' ORDER BY "depot_shipment"."reference" ASC LIMIT 10
        returned SHP-0021 ... SHP-0025


The offset climbs by ten per page while the limit stays put, except on the last page where it narrows to the five remaining rows. With twenty-five rows this costs nothing; with two million, OFFSET 1990 means the database locates and discards 1,990 rows before returning ten, and that work grows linearly with the page number. The keyset query asks a different question — rows after a known reference — which an index on that column can seek to directly, so the cost is the same for the first page and the ten-thousandth. What it gives up is arbitrary page numbers: there is no offset to jump to, only "the next ten after this value".


Edge Cases and Gotchas

  • Order by something unique, or add the primary key. Ordering on a non-unique column leaves ties in an undefined order, so order_by("status", "id") is stable where order_by("status") is not.
  • The count query can dominate. On a large filtered table, COUNT(*) may cost more than the page itself; if an approximate total is acceptable, or the UI only needs "is there a next page", fetch per_page + 1 rows and skip the count entirely.
  • Slicing a sliced queryset does not compose. queryset[:20][5:] applies bounds to bounds; take one slice from the full queryset instead. And a queryset that has already been sliced cannot be filtered or ordered afterwards.
  • Paginator also accepts a list. Handy for in-memory collections, but it then loses laziness entirely — the whole list is already in memory, so pagination saves nothing but display work.
  • Pages shift under concurrent writes. A row inserted before the current offset pushes one row from page 2 onto page 3 between requests, and offset pagination has no defence against it; keyset pagination does, because it anchors on a value rather than a position.

Summary

A page is a lazy slice compiled into LIMIT/OFFSET, paired with a COUNT(*) that makes page arithmetic possible. Ordering is what makes the slice meaningful, and the offset is what makes deep pages expensive.

  • Constructing a Paginator runs nothing; taking a page runs two queries — a count and a LIMIT/OFFSET slice carrying the same filters.
  • Only the rows for that page are fetched, so pagination is a database operation rather than a Python one.
  • An unordered queryset triggers UnorderedObjectListWarning, because LIMIT/OFFSET over unordered rows can return overlapping or missing pages.
  • page() raises EmptyPage and PageNotAnInteger; get_page() clamps bad input to a valid page, which suits a page number coming from a query string.
  • OFFSET n makes the database walk and discard n rows, so deep pages get slower; keyset pagination filters on the last value seen and stays flat, at the cost of arbitrary page jumps.

Trebuie să fii autentificat pentru a accesa laboratorul cloud.

Autentifică-te