Last modified: Dec 03, 2026
Django Search Results Pagination
Adding pagination to Django search results is a common task. It keeps your pages fast and easy to read. This guide walks you through it step by step.
You will learn how to combine a search query with Django's built-in Paginator class. The examples are simple and beginner friendly.
Why Pagination Matters for Search
Search can return many rows. Showing all rows on one page slows the browser and confuses users.
Pagination splits results into smaller pages. Users can move forward and back with ease. The database loads less data at once.
Good pagination also keeps your query string intact. That means the search term survives when the user clicks page two.
Setting Up a Simple Search View
Start with a basic view that filters a model. We will use a Book model with a title field.
# models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
def __str__(self):
return self.title
Now create a view that reads a search term from the request. It filters books by title.
# views.py
from django.shortcuts import render
from .models import Book
def book_search(request):
query = request.GET.get("q", "") # read the search term
results = Book.objects.all()
if query:
results = results.filter(title__icontains=query) # case-insensitive match
return render(request, "search.html", {"results": results, "query": query})
This works fine for small data sets. But it loads every match at once. Let's fix that with pagination.
Adding the Paginator
Django ships with a Paginator class. Import it and wrap your queryset.
# views.py
from django.shortcuts import render
from django.core.paginator import Paginator
from .models import Book
def book_search(request):
query = request.GET.get("q", "")
results = Book.objects.all()
if query:
results = results.filter(title__icontains=query)
# create a paginator with 10 books per page
paginator = Paginator(results, 10)
# get the page number from the URL, default to 1
page_number = request.GET.get("page")
page_obj = paginator.get_page(page_number)
return render(request, "search.html", {"page_obj": page_obj, "query": query})
The get_page method is safe. It handles missing or invalid page numbers. If the page is out of range, it returns the last page.
You can also use page directly, but get_page is more forgiving. For beginners, it is the better choice.
Updating the Template
Your template now receives a page_obj instead of a plain queryset. Loop over it the same way.
<!-- search.html -->
<h1>Search Books</h1>
<form method="get">
<input type="text" name="q" value="{{ query }}">
<button type="submit">Search</button>
</form>
<ul>
{% for book in page_obj %}
<li>{{ book.title }} by {{ book.author }}</li>
{% empty %}
<li>No results found.</li>
{% endfor %}
</ul>
The loop works because page_obj is iterable. Each item is a model instance.
Building Page Navigation Links
Users need links to move between pages. Keep the search query in the URL.
<!-- pagination controls -->
<div class="pagination">
{% if page_obj.has_previous %}
<a href="?q={{ query }}&page={{ page_obj.previous_page_number }}">Previous</a>
{% endif %}
<span>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</span>
{% if page_obj.has_next %}
<a href="?q={{ query }}&page={{ page_obj.next_page_number }}">Next</a>
{% endif %}
</div>
The has_previous and has_next methods tell you if a link is possible. The previous_page_number and next_page_number methods give you the target page.
Always include q={{ query }} in the link. Without it, the search term is lost on page change.
Handling Empty and Invalid Pages
What if the page number is 99 but there are only 3 pages? get_page returns the last page. That is helpful.
What if there are no results at all? The paginator still works. It returns an empty page object.
Page 1 of 1
No results found.
This keeps your template simple. You don't need extra checks for edge cases.
Using Class-Based Views
Many Django projects use class-based views. You can add pagination there too with the paginate_by attribute.
# views.py
from django.views.generic import ListView
from .models import Book
class BookSearchView(ListView):
model = Book
template_name = "search.html"
paginate_by = 10 # 10 books per page
def get_queryset(self):
query = self.request.GET.get("q", "")
qs = Book.objects.all()
if query:
qs = qs.filter(title__icontains=query)
return qs
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["query"] = self.request.GET.get("q", "")
return context
With this setup, the template receives page_obj and paginator automatically. You can reuse the same navigation block.
Class-based views reduce boilerplate. They are a good fit for larger projects. If you are still learning the basics of classes, the Python class basics for beginners guide is a solid starting point.
Keeping the Query String Clean
Hardcoding ?q=... works, but it breaks when you add filters. A cleaner approach uses the request's query dictionary.
You can copy the query parameters and replace only the page value. This keeps other filters intact.
# template tag or context helper
def build_page_url(request, page_number):
params = request.GET.copy() # copy existing parameters
params["page"] = page_number # set the new page
return params.urlencode() # build a safe query string
This small helper avoids bugs when your search form grows. It also handles URL encoding for you.
Performance Tips
Pagination still runs a count query. For very large tables, that count can be slow.
Use Paginator with care on big data sets. Consider database indexes on the fields you search.
An index on the title field makes icontains faster in many databases. Test with your real data before shipping.
You can also limit the number of pages shown. Showing ten page links is enough for most users.
Common Mistakes to Avoid
One common mistake is forgetting to pass the query to the template. The pagination links then drop the search term.
Another mistake is using page without error handling. A bad URL like ?page=abc raises an error. get_page avoids this.
Finally, do not slice the queryset before paginating. Slicing and pagination together cause confusing results.
If you want to understand how Django models and classes relate under the hood, the inheritance in Python explained article helps clarify the object model behind class-based views.
Testing Your Pagination
Write a simple test to confirm the page size. Create a few books and request page one.
# tests.py
from django.test import TestCase
from .models import Book
class SearchPaginationTest(TestCase):
def test_page_size(self):
for i in range(25):
Book.objects.create(title=f"Book {i}", author="Author")
response = self.client.get("/search/?q=Book")
self.assertEqual(len(response.context["page_obj"]), 10) # 10 per page
self.assertEqual(response.context["page_obj"].paginator.num_pages, 3)
Ran 1 test in 0.042s
OK
Tests catch regressions early. They also document how pagination should behave.
Wrapping Up
Adding pagination to Django search results takes a few lines. Import Paginator, wrap your queryset, and read the page number from the request.
Use get_page for safety. Keep the search query in every link. Update your template to loop over page_obj.
With these steps, your search pages stay fast and friendly. Users get clear navigation, and your database does less work.
Start with the function-based example, then move to class-based views when you feel ready. Both approaches share the same paginator underneath.