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)
But Django was actually doing something like:
1 query → fetch all orders
+ N queries → fetch each customer's data
----------------------------------------
101 queries for 100 orders 😬
The fix was simple:
orders = Order.objects.select_related("customer")
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:
Have you encountered an N+1 query that was surprisingly difficult to find?
Top comments (0)