Skip to the page

Django · Concept

select_related or prefetch_related

The 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

  1. Which one works for many-to-many and reverse foreign keys?
  2. You only want each author's published books, newest first. How do you prefetch that?
  3. You prefetched order.items, then wrote order.items.filter(active=True) inside a loop. How many queries now?
  4. When can select_related make a query slower?
  5. 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 inside Prefetch, or use annotate(Count(...)).
  • select_related across several wide tables can return huge, repeated rows; prefetch with very large IN lists 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_RAISE raises FieldFetchBlocked, 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 voice

Practise 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.

Start your free interview