Skip to the page

Django and DRF · core

QuerySets, select_related, prefetch_related and the N+1 problem

QuerySets are lazy and cache their results. A foreign key read in a loop causes one query per row. select_related joins in SQL, prefetch_related runs one extra query and joins in Python, and annotate counts in the database.

The notes

What you must know

  • QuerySets are lazy: filter() and order_by() run no SQL. SQL runs when you evaluate: if qs, list(qs), iteration, len().
  • if qs loads every row into memory. Use qs.exists() (SELECT 1 ... LIMIT 1) to check for rows and qs.count() for a count.
  • After a QuerySet is evaluated, count() and slicing use the cached list with no new query. On a fresh QuerySet, count() is SELECT COUNT(*) and [:10] is LIMIT 10.
  • N+1: a lazily loaded foreign key (order.customer) in a loop runs one query per order. Fix with select_related("customer").
  • select_related: one query with a JOIN, for forward foreign keys and one-to-one fields. prefetch_related: one extra query per relation (WHERE id IN (...)) joined in Python, for many-to-many and reverse foreign keys.
  • Prefetch("books", queryset=..., to_attr=...) 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. Use annotate(Count(...)) or Exists(...) instead.
  • A SerializerMethodField that runs obj.items.filter().count() is a hidden N+1. Put the fix in get_queryset() so every action uses it. Use a stable order_by for pagination.
  • Test it: assertNumQueries (TestCase) or django_assert_num_queries and django_assert_max_num_queries (pytest-django), on list endpoints with several rows. Django 6.1 adds fetch modes such as FETCH_PEERS and FETCH_RAISE.

The red pen

Common traps: mistake → fix

  • Mistake: QuerySet code that looks short runs one query

    Fix: every foreign key read in a loop can run its own query.

  • Mistake: prefetch_related makes later filters free

    Fix: calling filter() on a prefetched manager runs a new query.

  • Mistake: Staging looked fine, so the code is fine

    Fix: staging had 12 products; the query count grows with page size.

  • Mistake: if qs: is the way to check existence

    Fix: it loads the entire result; use exists().

Easy to hard

Questions interviewers ask, easy to hard

  1. How many queries does this code run, and on which lines?
  2. What is the difference between select_related and prefetch_related and what SQL does each run?
  3. A DRF list endpoint returns 50 orders with items and products. How many queries and how do you fix it?
  4. After a release, p95 went from 300 ms to 2.8 s. The queries look short and many. What do you do?
  5. How do you stop an N+1 from coming back?

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview