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.
