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
prefetch_related("customer")select_related("customer")(Correct option).only("customer").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.