Answer guide
Read the answer guide
The N+1 problem happens when you load a list of objects with one query and then trigger one extra query per object to read a related record, giving N+1 queries in total. For a single-valued relation such as a foreign key, select_related fetches the related row in the same query with a join. For collections and many-to-many relations, prefetch_related runs one extra query for all parents and joins the results in Python. I would look at the query count with Django Debug Toolbar or assertNumQueries, and compare timings before and after.
What the interviewer is assessing
Knowing how Django's ORM causes extra queries and which tool suits which relationship.
A strong answer covers
- One query loads a list, then each object triggers an extra query for its related record, giving N+1 queries in total.
- select_related fetches foreign key or one-to-one related rows in the same query using a join.
- prefetch_related runs one extra query for all parents and joins results in Python, suiting many-to-many and reverse relations.
- Check query count with Django Debug Toolbar or assertNumQueries and compare timings before and after.
- Apply these only to relations the page actually uses, rather than everywhere.
Common mistakes
- Using prefetch_related or select_related everywhere without checking what the page really needs.
- Not knowing the difference between a SQL join and a separate batched query.
Practise a follow-up
- How would you detect N+1 queries in a Django view automatically during tests?
- When does a prefetch fetch too much data, and what would you use instead?