Opening Scenario
You're building a page that lists the 50 most recent orders, with each order showing the customer's name and the list of products in the order.
Your code looks clean:
orders = Order.objects.order_by('-created_at')[:50]
for order in orders:
print(order.customer.name, order.items.all())In development, with 3 orders in the database, it loads in 12ms. You ship it to production. The page takes 4 seconds to load for some users, 8 seconds for others. Your database CPU is high. Your query count metric shows 101 queries for a single page load.
You haven't done anything obviously wrong. The ORM is handling the queries. What's going on?
Question Progression
Q1: Why are 101 queries running for a page that shows 50 orders?
Question: You asked for 50 orders. That's one query. Where are the other 100 coming from?
Reasoning: Your loop accesses order.customer…
In the full tutorial
- Closing: When to Reach for This