← Back to Django, page 1

django-0018 · Medium mid

What is the N+1 query problem in Django, and how do select_related and prefetch_related fix it?

N+1 happens when one query loads a list and then each item triggers another query for a related object. select_related follows ForeignKey and OneToOne links with a SQL JOIN in the same query. prefetch_related runs one extra query per relation for many-valued links (reverse ForeignKey, ManyToMany) and joins the results in Python. Prefetch objects let you filter or order the prefetched rows.

Full answer

Accessing a related object on a model instance runs a query the first time. In a loop that becomes one query for the list plus one per row:

python
for s in Student.objects.all():   # 1 query
    print(s.class_room.name)       # +1 query per student

With 500 students that is 501 queries. Each is fast alone, but the round trips add up and the page gets slow under load.

select_related("class_room") adds a SQL JOIN so the class room comes back in the same row. It works for forward ForeignKey and OneToOneField (and reverse OneToOne), and can follow chains: select_related("class_room__school").

prefetch_related("marks") is for relations that return many objects per row: reverse ForeignKey (student.marks) and ManyToMany. A JOIN there would repeat each student once per mark, so Django instead runs a second query (WHERE student_id IN (...)) and stitches results together in Python. Total: 2 queries no matter how many students.

Prefetch("marks", queryset=Mark.objects.filter(score__gte=70), to_attr="good_marks") customises the second query and stores the result in a list attribute.

Things that silently undo a prefetch: calling .filter() on the related manager inside the loop (s.marks.filter(...)) creates a new query each time. Filter in the Prefetch queryset instead.

How to find N+1: Django Debug Toolbar, assertNumQueries in tests, CaptureQueriesContext, or logging django.db.backends in development. Django 5.x has no automatic fix, so make query counts part of tests for list pages and API endpoints.

python
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.db import models, connection
from django.test.utils import CaptureQueriesContext


class ClassRoom(models.Model):
    name = models.CharField(max_length=10)
    class Meta:
        app_label = "school"


class Student(models.Model):
    name = models.CharField(max_length=40)
    class_room = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name="students")
    class Meta:
        app_label = "school"


class Mark(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
    subject = models.CharField(max_length=20)
    score = models.IntegerField()
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    for m in (ClassRoom, Student, Mark):
        editor.create_model(m)

a, b = ClassRoom.objects.create(name="10A"), ClassRoom.objects.create(name="10B")
for i, (name, room) in enumerate([("Asha", a), ("Ravi", a), ("Kiran", b), ("Meera", b)]):
    s = Student.objects.create(name=name, class_room=room)
    Mark.objects.create(student=s, subject="Maths", score=60 + i * 10)
    Mark.objects.create(student=s, subject="Science", score=55 + i * 8)

from django.db.models import Prefetch

def count_queries(fn):
    with CaptureQueriesContext(connection) as ctx:
        fn()
    return len(ctx.captured_queries)

naive = lambda: [s.class_room.name for s in Student.objects.all()]
joined = lambda: [s.class_room.name for s in Student.objects.select_related("class_room")]
print("FK naive:", count_queries(naive), "| select_related:", count_queries(joined))

naive_marks = lambda: [[m.score for m in s.marks.all()] for s in Student.objects.all()]
prefetched = lambda: [[m.score for m in s.marks.all()] for s in Student.objects.prefetch_related("marks")]
print("reverse FK naive:", count_queries(naive_marks), "| prefetch_related:", count_queries(prefetched))

qs = Student.objects.select_related("class_room").prefetch_related(
    Prefetch("marks", queryset=Mark.objects.filter(score__gte=75).order_by("-score"), to_attr="good_marks")
)
with CaptureQueriesContext(connection) as ctx:
    for s in qs:
        print(s.name, s.class_room.name, [m.score for m in s.good_marks])
print("queries:", len(ctx.captured_queries))

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): FK naive: 5 | select_related: 1 reverse FK naive: 5 | prefetch_related: 2 Asha 10A [] Ravi 10A [] Kiran 10B [80] Meera 10B [90, 79] queries: 2

Key points

  • N+1 = one list query plus one query per row
  • select_related uses JOINs for single-valued relations
  • prefetch_related uses a second IN query for many-valued relations
  • Prefetch() filters or orders the related rows
  • Filtering a related manager in a loop defeats prefetching

Common mistakes

  • Using select_related on a reverse ForeignKey or ManyToMany (it raises FieldError)
  • Calling .filter() on a prefetched relation inside the loop
  • Adding select_related everywhere and producing huge JOINs that load unused columns
  • Only noticing N+1 in production because tests never count queries

Follow-ups

  • How would you prefetch only the latest mark per student?
  • What does to_attr change compared with a normal prefetch?
  • How do you detect N+1 queries in DRF serializers?

Tips

  • Show the query counts before and after, numbers make the answer concrete
  • Explain why prefetch does not use a JOIN
  • Mention assertNumQueries as a regression guard