Full answer
paginator = Paginator(Student.objects.order_by("name"), per_page=10)
page = paginator.get_page(request.GET.get("page"))get_page() never raises: a missing, non-numeric or out-of-range page number returns page 1 or the last page. The older page() raises PageNotAnInteger and EmptyPage.
Useful members:
paginator.count(total rows),paginator.num_pages,paginator.page_range.page.object_list, iteration over the page,page.number.page.has_next(),page.next_page_number(),page.has_previous().paginator.get_elided_page_range(number)gives a compact list like1 2 … 9 10 11 … 20for UI links.
Pitfalls:
- Unordered querysets give unstable pages (rows can repeat or vanish), and Django warns with
UnorderedObjectListWarning. countrunsSELECT COUNT(*)on every request. On huge tables this dominates; cache the count or use cursor-based (keyset) pagination, which filters withWHERE id > last_seen ORDER BY id LIMIT n.- Deep OFFSET (
page=50000) forces the database to skip rows. - Generic
ListViewsupportspaginate_by = 10and putspage_objandpaginatorin the template context.
In templates, build links with ?page={{ page_obj.next_page_number }} and keep other query parameters (filters) in the URL.
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.core.paginator import Paginator, EmptyPage
from django.db import models, connection
class Student(models.Model):
name = models.CharField(max_length=40)
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Student)
Student.objects.bulk_create(Student(name=f"S{i:02d}") for i in range(1, 24))
p = Paginator(Student.objects.order_by("name"), per_page=10)
page = p.get_page(2)
print(page.number, [s.name for s in page][:3], page.has_next(), page.has_previous())
print(p.count, p.num_pages, list(p.page_range))
print(p.get_page("abc").number, p.get_page(99).number, p.get_page(None).number)
try:
p.page(99)
except EmptyPage as exc:
print("EmptyPage:", exc)
last_seen = "S10" # keyset pagination: no OFFSET
nxt = Student.objects.filter(name__gt=last_seen).order_by("name")[:3]
print([s.name for s in nxt])
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 2 ['S11', 'S12', 'S13'] True True 23 3 [1, 2, 3] 1 3 1 EmptyPage: That page contains no results ['S11', 'S12', 'S13']
Key points
- get_page() is forgiving; page() raises for bad numbers
- Order the queryset before paginating
- count() query runs per request
- Keyset pagination scales better than OFFSET
- ListView has paginate_by
Common mistakes
- Paginating an unordered queryset
- Using page() with raw request input and crashing on bad values
- Using OFFSET pagination for millions of rows
- Dropping filter parameters from the pagination links
Follow-ups
- What is keyset pagination and its trade-offs?
- How would you avoid the COUNT query?
- How does DRF's PageNumberPagination relate to Paginator?
Tips
- Mention get_page vs page
- Warn about ordering
- Name keyset pagination