StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 12 · Query Optimization

Select Related Detail Page

mediumDjango ORMQuery Optimization—No data yet

Problem statement

In this Django project, implement the order history page inside a one-query budget. Declare the relations the page walks on the queryset in order_history in app/views.py, so the orders, their customers and those customers' regions all arrive in one statement. The page is correct today and costs a query per row for the customer plus another per row for the region, and nothing about what it shows may change.

Requirements

Implement:

  • the queryset in order_history in app/views.py

The following files are already implemented and provided: app/models.py, app/urls.py and the template, and none of them changes. Region holds a name. Customer holds a name and a region. Order holds a reference, a total and a customer, and orders its rows by reference. app/templates/app/order_history.html renders order.reference, order.customer.name, order.customer.region.name and order.total on every row. Several orders share one customer and several customers share one region, which is why joining only the first hop still costs one query per row: each order builds its own customer object with its own empty cache, so the region of a customer three orders share is fetched three times.

1. GET /orders/ - the chain arrives with the orders

  • Purpose: List every order with its customer, that customer's region, and the total.
  • Response:
  • 200 OK: the same rows the page shows today - the same reference, customer name, region name and total, in the same order. The content tests compare every row cell by cell.
  • The chain the page walks is Order -> customer -> region, and both hops belong in the join. Covering only customer leaves the region lookup firing once per row and the page still misses its budget.
  • Declare the relations on the queryset itself. Do not fetch the related rows yourself and stitch them together in Python.

2. The budget

  • One full render of /orders/ costs exactly 1 query, and that number does not move when the order book grows.
  • The tests count the queries around the whole request, template included, so a relation the join does not cover is paid for while the page renders and shows up in the count.
  • Do not re-query the orders after joining them: building a second queryset from the first one's ids throws the join away.

Notes

  • A forward ForeignKey or a OneToOneField is what a row can join to, and one row has exactly one of each, so the join still returns one row per order.
  • Relations chain with a double underscore and each name is a further join. Naming only the deepest step is enough, because a join cannot reach the region without passing through the customer.
  • select_related only changes how much arrives in one trip: the rows selected, their order and their values are identical with it and without it, which is why adding it is never allowed to change a page.
  • Do not touch the template, the models or their ordering.

More in Query Optimization

See the module
Prefetch Related CollectionsA course listing reads each course's tags and students one course at a time, and its filtered student list re-queries on every row. Batch both collections with prefetch_related and apply the filter and the ordering through a Prefetch object.—No data yetmediumLean Field LoadingThe exports page loads every article's full body just to list titles, and it works out its flag and its total by pulling all the rows into Python. Trim the query to the columns the page shows and let the database answer the two questions instead.—No data yetmediumDashboard Under BudgetThe team dashboard renders correctly and costs hundreds of queries: the members arrive alone, then every row fetches its role, that role's department, its tags, its projects and its activities one at a time. Rebuild the page's data layer so the same markup renders inside a six query budget, combining a chained join, three batched collections with a filtered Prefetch, a trimmed column list and an existence check.—No data yetmedium

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.