DEV Community

Bun Rong
Bun Rong

Posted on

I found an interesting N+1 problem in a Django application...

I recently found an interesting N+1 query problem in a Django application.

The code looked completely normal:

orders = Order.objects.all()

for order in orders:
    print(order.customer.name)
Enter fullscreen mode Exit fullscreen mode

But Django was actually doing something like:

1 query  → fetch all orders
+ N queries → fetch each customer's data
----------------------------------------
101 queries for 100 orders 😬
Enter fullscreen mode Exit fullscreen mode

The fix was simple:

orders = Order.objects.select_related("customer")
Enter fullscreen mode Exit fullscreen mode

Now Django can fetch the related customer data in the same query instead of querying the database for every order.

The interesting part isn't just knowing select_related().

The real challenge is finding where the N+1 queries are happening, especially when they come from serializers, templates, nested relationships, or code you didn't realize was triggering additional database queries.

I wrote a practical walkthrough covering how to detect N+1 queries in Django, measure the queries, and fix them with select_related(), prefetch_related(), and assertNumQueries().

👉 Read the full article:

How to Find and Fix N+1 Queries in Django — Rong

A practical guide to finding N+1 query problems in Django with django-debug-toolbar and assertNumQueries, and fixing them with select_related, prefetch_related and Prefetch.

favicon technicaldev.vercel.app



Have you encountered an N+1 query that was surprisingly difficult to find?

Top comments (0)