Repaso
Español
Backend & APIsIntermediateAPI-13

Listing 50 orders then accessing order.customer.name in a loop triggers 51 queries. In Django, the usual fix for this foreign key is…

Options

  1. prefetch_related("customer")
  2. select_related("customer") (Correct option)
  3. .only("customer")
  4. .raw()

Answer

select_related("customer")

Why

This is the N+1 problem: 1 query to get the orders, then 1 extra query per order to fetch its customer.

select_related("customer") loads orders and customers together in one query with a SQL JOIN.

prefetch_related uses a second query for all related rows at once (for many-to-many or reverse relations). In SQLAlchemy: joinedload / selectinload.

Remember

Loop that queries per item = N+1. Load related data up front.

Key terms

Practice this question in Repaso