Django · Concept
select_related or prefetch_related
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
When do you use select_related and when prefetch_related? What SQL does each one actually run?
Then
Follow-ups the interviewer asks next
- Which one works for many-to-many and reverse foreign keys?
- You only want each author's published books, newest first. How do you prefetch that?
- You prefetched
order.items, then wroteorder.items.filter(active=True)inside a loop. How many queries now? - When can
select_relatedmake a query slower? - What do Django 6.1's fetch modes add?
The answer
What a strong answer covers
select_related: one query with a SQL JOIN, for forward foreign keys and one-to-one fields (both directions). Name the relations; calling it with no arguments is deprecated in 6.1.prefetch_related: one extra query per relation (WHERE id IN (…)), joined in Python. For many-to-many, reverse foreign keys (author.book_set) and generic relations.Prefetch("books", queryset=Book.objects.filter(published=True).order_by("-published_on"), to_attr="published_books")filters and orders the prefetched rows.- Calling
.filter(),.order_by()or.count()on a prefetched manager runs a new query per object, so the N+1 comes back. Filter insidePrefetch, or useannotate(Count(...)). select_relatedacross several wide tables can return huge, repeated rows; prefetch with very largeINlists can be slow too. Measure.- Django 6.1 fetch modes:
QuerySet.fetch_mode(models.FETCH_PEERS)loads a missing foreign key (or deferred field) for all objects from the same QuerySet on first access, like an on-demand prefetch;FETCH_RAISEraisesFieldFetchBlocked, useful in tests to catch lazy loads.
The red pen
Common traps
Avoid:"prefetch_related does a join"; using select_related on a many-to-many (it raises FieldError); thinking Django caches related objects across requests.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.