The Analogy: A Warehouse Order-Picking Floor
Imagine a large distribution warehouse. Orders arrive at a desk as pick lists -- sheets naming the cartons a customer wants. A picker with a cart walks the aisles and brings back what the sheet names. Here the aisles are the database, and every walk out onto the floor is a query. Crucially, writing and refining a pick list at the desk costs nothing: you can cross items out, add a sort order, and cap the quantity, and not one person has moved. The warehouse is only ever touched when a finished list is released to a picker.
That desk work is laziness. A supervisor can keep amending the same sheet -- only electronics, only what is in stock, sorted by aisle so the route is short, only the first twenty cartons -- and none of it sends anyone walking. When the sheet is finally released, the picker makes one optimized loop and returns with everything at once. The "first twenty" line matters: the picker stops as soon as twenty are on the cart rather than pacing the whole building, exactly as a database applies LIMIT instead of reading every row.
Now the trap. A sheet says: bring these fifty cartons, and for each carton also bring its handling slip from the office. A careless floor sends the picker for the fifty cartons in one trip, then back to the office once per carton -- fifty more trips -- collecting slips one at a time: fifty-one trips for one order. A disciplined floor grabs all fifty cartons, reads off their ids, and collects every slip in a single second sweep: two trips. Taping each slip to its carton so both come back in the same grab is tighter still -- one trip. Those three floors are the naive loop, prefetch_related, and select_related.
The pick list is byte-for-byte identical no matter which floor runs it; the difference is invisible on paper. In a nearly empty warehouse -- a handful of cartons, which is what a developer's test database holds -- fifty-one trips finish in seconds and every test passes. The day the warehouse is full and a single order touches thousands of cartons, that same unchanged list has the picker walking for hours. The bug shipped in the one place nobody was looking: not in the list, but in how quietly the floor chose to walk it.
Syntax or Core Structure
Real Django first. A QuerySet is a description of a query, not its result. Building one -- filtering, ordering, slicing -- touches nothing; the database is hit only when the QuerySet is evaluated.
qs = Product.objects.filter(active=True) # no query
qs = qs.filter(price__lt=100) # still no query
qs = qs.order_by("name") # still no query
qs = qs[:3] # still no query -- becomes LIMIT 3
for product in qs: # NOW one SELECT runs
print(product.name)
We can make that laziness visible by reducing the ORM to a plain-Python REPL: an in-memory list of rows and a counter that ticks once per trip to the database. The QuerySet below records filters and a cap but does not scan the rows until it is iterated or counted.
PRODUCTS = [
{"id": 1, "name": "pump", "price": 120, "active": True},
{"id": 2, "name": "hose", "price": 40, "active": True},
{"id": 3, "name": "clamp", "price": 15, "active": False},
{"id": 4, "name": "valve", "price": 80, "active": True},
{"id": 5, "name": "gauge", "price": 200, "active": True},
]
queries = {"n": 0}
class QuerySet:
def __init__(self, rows, preds=None, cap=None):
self.rows, self.preds, self.cap = rows, preds or [], cap
self.cache = None
def filter(self, **kw):
p = lambda r: all(r[k] == v for k, v in kw.items())
return QuerySet(self.rows, self.preds + [p], self.cap)
def head(self, n):
return QuerySet(self.rows, self.preds, n)
def _match(self):
return [r for r in self.rows if all(p(r) for p in self.preds)]
def __iter__(self):
if self.cache is None:
queries["n"] += 1 # one trip to the floor
rows = self._match()
self.cache = rows[:self.cap] if self.cap is not None else rows
return iter(self.cache)
def count(self):
queries["n"] += 1 # COUNT(*), loads nothing
return len(self._match())
queries["n"] = 0
active = QuerySet(PRODUCTS).filter(active=True) # builds, no query
page = active.head(3) # builds, no query
print("built the chain, queries so far:", queries["n"])
print("first page (head 3):", ",".join(p["name"] for p in page))
print("queries after iterating:", queries["n"])
print("count(active):", active.count())
print("queries after count:", queries["n"])
Output:
built the chain, queries so far: 0
first page (head 3): pump,hose,valve
queries after iterating: 1
count(active): 4
queries after count: 2
Building active and page walks nobody: the counter is still zero. Iterating page fires exactly one query and caches its three names. Then active.count() is a separate object, so it fires its own query -- reusing a variable is free, but re-deriving the set pays again. That single fact drives every mistake below.
Technical Depth: Evaluation, Caching and Killing N+1
What forces evaluation
Knowing which operations touch the database -- and whether they drag rows into memory -- is most of ORM performance.
| Operation | Hits the database? | Rows loaded |
|---|---|---|
| iteration, list(qs) | yes | all matching |
| len(qs) | yes | all matching |
| qs.count() | yes | none, COUNT(*) |
| bool(qs), if qs | yes | at most one |
| qs.exists() | yes | none |
| slicing qs[:n] | no, adds LIMIT | deferred |
| qs.first(), qs.last() | yes | one |
The pairs that look interchangeable are not. exists() asks the database a yes/no question; len() hauls every matching row back to answer the same question in Python.
# cheap: the database stops at the first row, or returns one number
if Product.objects.filter(sku=sku).exists():
...
n = Product.objects.filter(active=True).count()
# expensive: every matching row crosses the wire to learn one fact
if len(Product.objects.filter(sku=sku)) > 0:
...
n = len(Product.objects.filter(active=True))
The N+1 problem, and the two tools that end it
The classic bug: iterate a set of parent rows and touch a related object on each one. The parent list is one query; each related access is another. For N parents that is 1 + N queries, and it hides perfectly when N is small. Reduce it to a REPL with the same query counter:
ORDERS = [
{"id": 1, "customer": 10},
{"id": 2, "customer": 11},
{"id": 3, "customer": 10},
]
CUSTOMERS = {10: "Acme", 11: "Globex"}
def naive():
q = 1 # SELECT * FROM orders
names = []
for o in ORDERS: # one extra query per order
q += 1
names.append(CUSTOMERS[o["customer"]])
return q, names
def select_related():
q = 1 # one JOIN pulls the customer inline
return q, [CUSTOMERS[o["customer"]] for o in ORDERS]
def prefetch_related():
q = 2 # orders, then ONE batched customer query
return q, [CUSTOMERS[o["customer"]] for o in ORDERS]
for label, fn in [("naive", naive), ("select_related", select_related), ("prefetch_related", prefetch_related)]:
q, names = fn()
print(f"{label:16}: queries={q} {','.join(names)}")
Output:
naive : queries=4 Acme,Globex,Acme
select_related : queries=1 Acme,Globex,Acme
prefetch_related: queries=2 Acme,Globex,Acme
Three orders give the naive loop 1 + 3 = 4 queries; the output rows are byte-identical, which is exactly why the bug is invisible. select_related folds a forward foreign key into a single JOIN; prefetch_related runs a second batched query and stitches the results in Python. Pick by relation type:
| Tool | Relation it follows | Queries added |
|---|---|---|
| select_related | ForeignKey, OneToOne forward | 0, folded into a JOIN |
| prefetch_related | ManyToMany, reverse FK | 1 batched query per relation |
Real World Example: An Orders Dashboard and Its Query Budget
A dashboard lists every order with its customer name and amount, then sums revenue and finds the biggest customer. The rendered page is identical whether it was built with one query or five; only the query budget differs. The stand-in below renders the same dashboard through a naive loader and an optimized one and reports both counts, so the cost that production would feel is made explicit here.
CUSTOMERS = {10: "Acme", 11: "Globex"}
ORDERS = [
{"id": 1, "customer": 10, "cents": 1500},
{"id": 2, "customer": 11, "cents": 500},
{"id": 3, "customer": 10, "cents": 2000},
{"id": 4, "customer": 11, "cents": 750},
]
def dashboard(loader):
if loader == "naive":
queries = 1 + len(ORDERS) # orders + one customer lookup each
else:
queries = 1 # select_related: a single JOIN
lines = [f" {CUSTOMERS[o['customer']]} {o['cents']}" for o in ORDERS]
revenue = sum(o["cents"] for o in ORDERS)
by_cust = {}
for o in ORDERS:
name = CUSTOMERS[o["customer"]]
by_cust[name] = by_cust.get(name, 0) + o["cents"]
top = max(by_cust, key=lambda k: by_cust[k])
return queries, lines, revenue, by_cust, top
qn, lines, revenue, by_cust, top = dashboard("naive")
qo = dashboard("optimized")[0]
print("rows:")
for ln in lines:
print(ln)
print("revenue:", revenue)
print("by customer:", ", ".join(f"{k}={v}" for k, v in by_cust.items()))
print("top customer:", top)
print("naive queries:", qn)
print("optimized queries:", qo)
print("outputs identical:", dashboard("naive")[1:] == dashboard("optimized")[1:])
Output:
rows:
Acme 1500
Globex 500
Acme 2000
Globex 750
revenue: 4750
by customer: Acme=3500, Globex=1250
top customer: Acme
naive queries: 5
optimized queries: 1
outputs identical: True
The two loaders return byte-for-byte identical rows, revenue, per-customer totals, and top customer; the only difference is the query count, five against one. That is the whole lesson in one output block: correctness and cost are independent axes. A page can be perfectly correct in every test and still fall over in production purely on the query budget the tests never measured.
The revenue and per-customer roll-up here are computed by looping the four orders in Python. That is fine for four rows and wrong for four million: the scale-correct version pushes the work into the database with ORDERS.values("customer").annotate(Sum("cents")), which returns two grouped rows instead of dragging every order across the wire to be summed in the application.
This code has real flaws worth naming. The naive figure 1 + len(ORDERS) assumes a fresh query for every order, but Django's per-request instance cache can dedupe the repeated customer 10, so the true naive cost is often below the worst case shown -- the model overstates to make the point visible. The cents are summed as bare integers with no currency, so orders in different currencies would add silently and wrongly. And outputs identical: True holds only because ORDERS has a fixed list order; a real QuerySet with no order_by can return the same rows in a different order between two loaders, at which point the equality flips -- the dashboard has no ORDER BY and is quietly relying on luck.
Common Mistakes
- Calling len(qs) to get a count.
len()loads every matching row into memory;qs.count()issuesSELECT COUNT(*)and loads nothing. Reach forlen()only when you already need the rows.
- Re-deriving a QuerySet inside a loop. Each
Model.objects.filter(...)re-run in a loop body is a fresh query. Build it once outside the loop, or materialise withlist()if you must reuse the rows.
- Touching a related object per row without prefetching.
order.customer.nameinside a loop over orders is the textbook N+1. Addselect_related("customer")for a forward FK.
- Counting then iterating when you needed the rows anyway.
qs.count()followed byfor x in qsis two queries. Iterate once, keep the list, and uselen(list).
- Slicing after evaluation.
list(qs)[:20]loads the whole table then throws most away;qs[:20]becomesLIMIT 20and never fetches the rest.
- Using count() > 0 instead of exists().
exists()lets the database stop at the first matching row;count() > 0may scan more than it needs.
- Calling select_related on a many-to-many or reverse FK. It cannot JOIN those into one row; you get an error or no effect. Those relations need
prefetch_related.
- Slicing an unordered QuerySet.
LIMITwithoutORDER BYreturns arbitrary rows that can change between runs. Alwaysorder_bybefore slicing or paginating.
- Filtering a prefetched relation in Python.
prefetch_related("items")then[i for i in o.items.all() if ...]re-hits the database or discards the cache; filter inside aPrefetch(queryset=...)instead.
Best Practices
- Ask the database yes/no and how-many questions directly. Prefer
exists()andcount()over materialising rows just to test or tally them.
- Match the prefetch tool to the relation.
select_relatedfor forwardForeignKey/OneToOne;prefetch_relatedforManyToManyand reverse foreign keys.
- Materialise once when you iterate more than once. Bind
rows = list(qs)and reuserows; do not let two loops trigger two scans.
- Aggregate in the database. Use
.annotate()and.aggregate()so grouping and sums run in SQL, not in a Python loop over every row.
- Order before you slice. Put a stable
order_byon any QuerySet you paginate or take[:n]from.
- Trim wide rows. Use
.only()and.defer()to avoid dragging large columns you will not render.
- Pin the query count in tests. Wrap hot paths in
assertNumQueries(n)so an accidental N+1 fails CI instead of production.
- Look at the SQL. Read
qs.query, enable query logging, or use Django Debug Toolbar in development to see exactly what runs.
Practice Exercises
- Add exists() to the stand-in. Give
QuerySetanexists()that ticks the counter once and returnsTrueat the first matching row, and show the counter stays at 1 regardless of how many rows match.
- Add line items and prefetch them. Extend the dashboard with a reverse relation (line items per order) and write a loader that keeps the total at two queries no matter how many orders there are.
- Write an assertNumQueries helper. Implement a function that resets the counter, runs a loader, and raises if the query count is not the expected number; use it to catch a deliberately reintroduced N+1.
- Aggregate in one pass. Rewrite
by_custas a single grouped pass that mimicsvalues("customer").annotate(Sum("cents")), and assert its output matches the Python-loop version exactly.