Problem statement
In this Django project, implement the four sections of the analytics report as ORM computations. Build top_categories_by_revenue, monthly_revenue, flagged_products and store_aggregates in app/report.py, each inside a budget of one query. Three of them were never written, so the report renders empty, and the fourth pulls every sale row back into Python to add the amounts up in a loop.
Requirements
Implement in app/report.py:
- top_categories_by_revenue(limit=3)
- monthly_revenue()
- flagged_products()
- store_aggregates()
The following files are already implemented and provided: app/models.py, app/views.py, app/urls.py and the template. Category holds a name. Product holds a sku, a name, a category (reverse name products), a price, a cost and a discontinued flag. Sale holds an amount, a sold_on date and a product (reverse name sales), and declares ordering = ("-sold_on",) in its Meta. sales_report at /report/ calls all four functions and hands their results to the template. app/report.py already holds the four names the view imports; store_aggregates is the Python loop described above and the other three are empty. Every section returns its rows; nothing prints and nothing is cached between calls.
1. top_categories_by_revenue(limit=3) - budget: 1 query
- Returns the highest-earning categories, each row carrying its own revenue under the name revenue.
- Revenue is the sum of the amount of every sale of every product in that category. A category that sold nothing is still a row, with a revenue of 0.00 rather than None, so do not filter on the relation.
- Rows come back by revenue descending, and two categories on the same revenue are ordered by name ascending.
- Only limit rows come back, chosen by the database rather than by slicing a list afterwards. The view calls the function without an argument, so the default of three is what the page shows.
- That one statement carries each piece where it really has to appear: a SUM( over the sale amount in the SELECT list - the part before the FROM - plus a GROUP BY clause and a LIMIT clause. A SUM( over some other column is the wrong sum.
2. monthly_revenue() - budget: 1 query
- Returns one row per month that has sales, oldest month first. A month without sales is absent.
- Each row is a values() dictionary with the keys month, sale_count and revenue: the first day of that month, how many sales fall in it, and the sum of their amount. Sales made on different days of one month belong to one row.
- Its SELECT list has to contain COUNT( and SUM(; its GROUP BY has to name exactly one thing, because two means a second column joined the grouping and shattered the months; and it has to ORDER BY that same one thing, ascending.
3. flagged_products() - budget: 1 query
- Returns the products the margin rule flags, each row carrying its own margin under the name margin.
- A product's margin is its price minus its cost, computed inside the query from the two columns. That subtraction has to be in the statement. Naming cost somewhere is not enough, because Django names every concrete column of Product in a default SELECT list, so every Product queryset ever written mentions it.
- A product is flagged when its margin is at or below 5.00, or strictly below a tenth of its price, and never when it is discontinued, however thin its margin is.
- A margin of exactly 5.00 is flagged; a margin of exactly a tenth of the price is not.
4. store_aggregates() - budget: 1 query
- Returns one dictionary with exactly the keys total_revenue, sale_count, average_sale, smallest_sale and largest_sale: the sum, the count, the mean, the smallest and the largest of every sale's amount.
- With no sales at all, total_revenue is 0.00 and sale_count is 0, while average_sale, smallest_sale and largest_sale stay None. The mean, smallest and largest of nothing are undefined, so do not coalesce them.
- This statement's SELECT list carries SUM(, COUNT(, MIN( and MAX(; for the mean, either AVG( or a SUM( divided by a COUNT( is fine.
- The statement has to carry no GROUP BY: a store-wide aggregate() collapses the table into one row, while a per-row annotate() holding the same five functions groups by every row and ships them all back.
5. An empty database
- top_categories_by_revenue, monthly_revenue and flagged_products each return an empty result and raise nothing.
- store_aggregates still reports all five keys: 0.00, 0, None, None, None.
Notes
- Four sections, one query each, four for the whole page. Reading every value off every row stays inside that budget, so a number fetched per row breaks it even when it is correct.
- The keyword is the name: revenue=Sum("products__sales__amount") is why the row carries revenue, and renaming it leaves the template reading nothing.
- A row with no related rows survives an annotation, because the join that collects them is a LEFT JOIN: Count is 0 and Max is None, while filter(sales__isnull=False) throws the row away.
- SUM over no rows is NULL. On a DecimalField the Coalesce fallback has to be a Decimal or carry output_field, or COALESCE(<decimal>, <integer>) raises FieldError: Expression contains mixed types.
- Slicing an ordered queryset becomes a LIMIT; ordering in the database and then slicing the list in Python ships every row first.
- A field a grouped query orders by joins its GROUP BY, so order a grouping by the columns it groups on, or by its own aggregates, and by nothing else. Meta.ordering is dropped from a grouped query since Django 3.1, so it cannot shatter the rows - but it does not order them either.
- The monthly ordering is checked in the SQL rather than in the rows on purpose: sqlite hands back the groups of a one-column GROUP BY in ascending key order whether you asked for it or not.
- & binds tighter than |, so an or-group inside a composed filter needs its own parentheses.
- Money is compared rounded to two decimal places, as a float, so neither trailing zeros nor the exponent the backend picks for an average matters.
- Do not reach for select_related or prefetch_related here; none of the four sections walks a relation row by row.
