StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 11 · ORM Aggregation & Annotation

Store Totals Aggregate

mediumDjango ORMAggregation50%1 of 2 solved

Problem statement

In this Django project, implement the store's five order metrics in the database instead of in Python. Build the body of store_metrics() in app/metrics.py as one aggregate() call that returns the revenue, the mean, the count and the two extremes. This replaces a loop that ships every order over the wire to add up a column the database could have added itself.

Requirements

Implement:

  • the body of store_metrics() in app/metrics.py

The following files are already implemented and provided: app/models.py, app/views.py, app/urls.py and the template. Order holds reference (unique), total (a DecimalField, the money the store charged) and an optional discount. Every metric is about total; discount is nullable and is not part of any of them. store_totals renders whatever store_metrics() returns, under the keys it returns, at /totals/. store_metrics() keeps its name and takes no arguments: the view imports it by that name.

1. store_metrics() - the five metrics, under these exact keys

  • total_revenue is the sum of every total, and is 0 rather than None for a store with no orders.
  • average_order_value is the mean total, and is None for an empty store.
  • order_count is how many orders there are, and is 0 for an empty store without any help.
  • smallest_order is the lowest total, and is None for an empty store.
  • largest_order is the highest total, and is None for an empty store.
  • The returned dictionary carries exactly those five keys and nothing else, for a seeded store and an empty one alike, and calling it against an empty store raises nothing.

2. The empty store

  • total_revenue is the one metric that has to be coerced, because the revenue of a store with no orders is zero. SUM, AVG, MIN and MAX over nothing all return SQL NULL, which arrives as None; COUNT is the exception and returns 0.
  • The other three stay None. The mean, the smallest and the largest of no orders are undefined, and reporting 0 for them would read as "an order of nothing", so do not coalesce those.

3. One query, and the database does the arithmetic

  • The whole set costs exactly one query, for a store with orders and for an empty one alike. A if not Order.objects.exists(): guard in front of the aggregate is a second query and fails the budget.
  • The SELECT list of that statement - the part before the FROM, which is what the database is being asked to compute - has to contain SUM(, AVG(, COUNT(, MIN( and MAX(.
  • 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.

Notes

  • Name each aggregate with a keyword argument. Passing one positionally - aggregate(Max("total")) - makes the ORM invent the key total__max, which is not a name anything else agreed to.
  • One aggregate() call is one SELECT; five separate calls would return the same five numbers and cost five round trips.
  • Coalesce needs both sides to be the same kind of field. Over a DecimalField, Coalesce(Sum("total"), Value(0)) raises FieldError: Expression contains mixed types; pass Value(Decimal("0.00")) or an explicit output_field.
  • Money comes back as Decimal, and two Decimal values are equal whatever their trailing zeros.
  • Stay inside aggregate(): this question needs no annotate(), no F() and no Q(), and no loop or Python sum(), min(), max() or len() over the rows.

More in ORM Aggregation & Annotation

See the module
Per-Category AnnotationThe category report builds its numbers with a COUNT and an AVG per category inside a Python loop. Annotate the category queryset instead, order it by an annotation, and group sales by month with values().100%1 of 1 solvedmediumF And Q ExpressionsRestocking reads a row into Python, adds to it and saves it back, so two deliveries recorded at once lose one of them, and the stock report compares every quantity against a number typed into the code. Move the arithmetic into the database with F expressions, compare a column against another column, and compose OR, AND and NOT into single filtered queries with Q objects.100%1 of 1 solvedmediumSales Analytics ReportThe analytics page renders empty because three of its four sections were never written, and the one that works pulls every sale row into Python to add the amounts up in a loop. Build all four sections as ORM computations - a limited revenue ranking, a monthly grouping, an F-based margin feeding a Q-filtered flag set, and a store-wide aggregate block - each inside one query.100%1 of 1 solvedmedium

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.