Django Django

What's the difference between `select_related()` and `prefetch_related()`?

Dima Nov 15, 2026

Short Answer

select_related() adds a SQL JOIN so the related rows arrive inside the same query; prefetch_related() issues one extra query per relation and matches the results up in Python. That difference decides where each one applies: a JOIN can only pull in a relation that contributes at most one row per result — a forward ForeignKey or a OneToOneField — while anything multi-valued, like a reverse foreign key or a ManyToManyField, would multiply every parent row by its children. Both exist to remove the same problem, the N+1 query, and both fill the same per-instance caches so that attribute access afterwards costs nothing.


How It Works

Django loads related objects lazily. A queryset fetches rows from one table, and the first time you touch shipment.carrier on an instance, the ORM issues a query for that carrier. Do it inside a loop over N shipments and you get one query for the list plus one per row — the N+1 pattern. It stays invisible in development, where N is three, and becomes the whole response time in production, where N is two hundred.

select_related() solves it by changing the SQL. The requested relations become INNER JOIN or LEFT OUTER JOIN clauses, their columns are added to the SELECT list, and Django builds both the parent and the related instance from a single row. One query returns everything. This works only when the relation is single-valued from the queryset's side: a forward ForeignKey, a OneToOneField, or a reverse one-to-one. Ask for anything else and you get a FieldError listing what is actually available, rather than a silently wrong query.

prefetch_related() solves it a different way, because for multi-valued relations a JOIN is the wrong shape. Three shipments with two scans each produce six joined rows, repeating every shipment column twice; at realistic sizes that duplication dominates the transfer, and it interferes with LIMIT because the row count no longer matches the object count. So Django runs the base query, collects the primary keys, and issues a second query along the lines of WHERE shipment_id IN (…). It then distributes the results onto the parent instances in Python. Two queries, no duplication, and each table's rows crossing the wire exactly once.

The result is the rule of thumb: select_related for the relations you can reach by following a single foreign key forwards, prefetch_related for the collections hanging off a reverse relation. They compose — select_related("carrier").prefetch_related("scans") is one JOINed query plus one extra — and prefetch_related also accepts a forward FK if you would rather pay a second query than widen the join.


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

The N+1 pattern

Three shipments, each with a carrier, listed in the most natural way possible.

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


class Carrier(models.Model):
    name = models.CharField(max_length=40)


class Shipment(models.Model):
    reference = models.CharField(max_length=20)
    carrier = models.ForeignKey(Carrier, related_name="shipments", on_delete=models.CASCADE)


class Scan(models.Model):
    shipment = models.ForeignKey(Shipment, related_name="scans", on_delete=models.CASCADE)
    dock = 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 Carrier, Scan, Shipment


def seed():
    with connection.schema_editor() as editor:
        editor.create_model(Carrier)
        editor.create_model(Shipment)
        editor.create_model(Scan)
    maersk = Carrier.objects.create(name="Maersk")
    hapag = Carrier.objects.create(name="Hapag-Lloyd")
    for reference, carrier in [("SHP-4471", maersk), ("SHP-4408", hapag), ("SHP-3157", maersk)]:
        shipment = Shipment.objects.create(reference=reference, carrier=carrier)
        Scan.objects.create(shipment=shipment, dock="dock-7")
        Scan.objects.create(shipment=shipment, dock="dock-9")
    connection.queries_log.clear()


# main.py
from bootstrap import Shipment, connection, seed

seed()

for shipment in Shipment.objects.order_by("reference"):
    print(f"{shipment.reference} carried by {shipment.carrier.name}")

print("queries run:", len(connection.queries))
print("SQL of the last query:", connection.queries[-1]["sql"])


SHP-3157 carried by Maersk
SHP-4408 carried by Hapag-Lloyd
SHP-4471 carried by Maersk
queries run: 4
SQL of the last query: SELECT "depot_carrier"."id", "depot_carrier"."name" FROM "depot_carrier" WHERE "depot_carrier"."id" = 1 LIMIT 21


One query for the shipments, then one per shipment for its carrier: four for three rows, and four hundred and one for four hundred. The last query is the detail worth noticing — it fetches carrier id = 1, which is Maersk, already loaded moments earlier for SHP-3157. The related-object cache lives on each model instance, not on the queryset, so two shipments sharing a carrier fetch it twice. Nothing in the loop looks expensive; the cost is entirely in what the attribute access does.


select_related() folds it into one JOIN

Replace main.py. The loop is unchanged; only the queryset construction differs.

# main.py
from bootstrap import Shipment, connection, seed

seed()

shipments = Shipment.objects.select_related("carrier").order_by("reference")
for shipment in shipments:
    print(f"{shipment.reference} carried by {shipment.carrier.name}")

print("queries run:", len(connection.queries))
print("joins in the SQL:", str(shipments.query).count("JOIN"))


SHP-3157 carried by Maersk
SHP-4408 carried by Hapag-Lloyd
SHP-4471 carried by Maersk
queries run: 1
joins in the SQL: 1


Four queries become one, and the reason is visible in the SQL: a single JOIN brings the carrier columns along with the shipment columns. Django constructs the Carrier instance from those extra columns and stores it in the shipment's cache before your code ever asks, so shipment.carrier.name reads memory. The row count is unchanged at three, because each shipment has exactly one carrier — which is precisely the condition that makes a JOIN the right tool here.

Try it: Change select_related("carrier") to prefetch_related("carrier"). The relation is the same foreign key; what values will the last two lines have? queries run: 2 and joins in the SQL: 0. prefetch_related works on a foreign key too, but differently: a second query fetches the carriers with WHERE id IN (...), and Python attaches them to the shipments. For a relation to a single object, the JOIN of select_related does the same job in one round trip.


prefetch_related() for the multi-valued side

Replace main.py. Now the loop crosses a reverse foreign key, where every shipment has many scans.

# main.py
from bootstrap import Shipment, connection, seed
from django.core.exceptions import FieldError

seed()

for shipment in Shipment.objects.all():
    list(shipment.scans.all())
print("without prefetch_related:", len(connection.queries), "queries")

connection.queries_log.clear()
for shipment in Shipment.objects.prefetch_related("scans"):
    list(shipment.scans.all())
print("with prefetch_related   :", len(connection.queries), "queries")

try:
    list(Shipment.objects.select_related("scans"))
except FieldError as exc:
    print("select_related('scans') :", exc)

joined = Shipment.objects.filter(scans__isnull=False).count()
print(f"a join over scans yields {joined} rows for {Shipment.objects.count()} shipments")


without prefetch_related: 4 queries
with prefetch_related   : 2 queries
select_related('scans') : Invalid field name(s) given in select_related: 'scans'. Choices are: carrier
a join over scans yields 6 rows for 3 shipments


The same N+1 appears, and prefetch_related collapses it to two: one for the shipments, one fetching every matching scan by parent id. select_related("scans") is refused outright, and the error names the only field it could have joined — Django will not build a query whose row count no longer matches the object count. The last line is the justification: joining scans turns three shipments into six rows, and each extra scan per shipment multiplies the duplication further. Two clean queries beat one query carrying every parent column repeatedly.

Try it: In the loop with prefetch_related("scans"), change shipment.scans.all() to shipment.scans.filter(dock="dock-7"). The prefetch is still there; how many queries does the second line report? 5, more than the version without prefetch. The prefetch's two queries ran for nothing: filter() builds a new queryset that cannot be answered from the cache, so every shipment issues its own query. The prefetch cache only serves .all().


Edge Cases and Gotchas

  • Filtering a prefetched relation re-queries. shipment.scans.filter(dock="dock-7") is a new queryset and ignores the prefetched cache. Use Prefetch("scans", queryset=Scan.objects.filter(...)) to prefetch the narrowed set instead, then iterate it plainly.
  • They chain through relations with __. select_related("carrier__region") follows two foreign keys in one JOIN, and prefetch_related("scans__operator") prefetches a relation of a prefetched object. Each extra level on select_related widens the row.
  • A nullable FK becomes a LEFT OUTER JOIN. select_related on a nullable relation cannot use an inner join without dropping rows, so the query widens and the attribute may still be None.
  • select_related() with no arguments follows every non-null FK. That is rarely what you want on a wide model; name the relations explicitly.
  • only() and defer() interact badly with both. Deferring a field that a related object needs triggers a fresh query per instance, quietly reintroducing the N+1 you just removed.

Summary

Both methods eliminate the same N+1 pattern by loading related objects up front, and they differ in how. select_related widens the query with a JOIN and works only where the relation contributes one row per result; prefetch_related runs a second query and joins in Python, which is what makes it safe for collections.

  • select_related produces one query containing JOINed columns; prefetch_related produces one extra query per relation, matched up in Python.
  • Use select_related for forward ForeignKey and OneToOneField; use prefetch_related for reverse foreign keys and ManyToManyField.
  • Asking select_related for a multi-valued relation raises FieldError rather than producing a query whose rows outnumber the objects.
  • The related-object cache is per instance, so without either method two rows sharing one related object fetch it twice.
  • They compose freely, and prefetch_related also accepts a forward FK when a second query is preferable to a wider join.

You need to be logged in to access the cloud lab.

Log in