BeginnerCoder

Lesson 19 — Avoiding N+1

The N+1 query problem

If you show 100 orders and look up each order's user with a separate database query, that is 1 query for the orders + 100 for users = N+1 queries, and the page gets slow. The fix is to fetch all needed users once and keep them in a dict. Django does this with select_related / prefetch_related.

Here a counter shows how many "queries" we make.

Note: the exercise runs in your browser without Django installed, so it is a small plain-Python simulation of what Django does for you.

Why it matters: N+1 is the most common reason a Django page is slow — and the fix is a few lines.

Want it another way?
Task

Replace the per-order lookup with one fetch_users() call before the loop, so queries drops to 1.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Django Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.