Pagination (Django)
Pagination splits a long list of results into pages in Django. The Paginator class powers function-based and template paging, ListView offers paginate_by, and DRF provides pagination classes for APIs.
Django
Showing thousands of rows at once is slow and unwieldy, so you serve one page at a time. Django's core Paginator(object_list, per_page) gives you page objects with .object_list, .has_next, .has_previous, and .number, and you read the requested page from the query string.
In class-based views, ListView's paginate_by attribute turns on pagination automatically and exposes page_obj and is_paginated to the template. In DRF, pagination classes (PageNumberPagination, LimitOffsetPagination) add page metadata to JSON responses, configured globally or per view.
Always order your queryset before paginating (order_by) so the slices are stable; otherwise the database may return rows in different orders across page requests, causing items to repeat or vanish.
Syntax
from django.core.paginator import Paginator
Paginator(qs, 20).get_page(n)Examples
Python
from django.core.paginator import Paginator
def post_list(request):
posts = Post.objects.order_by("-created")
page = Paginator(posts, 10).get_page(request.GET.get("page"))
return render(request, "list.html", {"page": page})