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

F And Q Expressions

mediumDjango ORMQuery Expressions100%1 of 1 solved

Problem statement

In this Django project, implement the inventory queries as expressions the database evaluates. Build restock, needs_reorder and the four composed reads in app/queries.py using F() for column arithmetic and column comparison and Q() for composed conditions. This closes a restock that loses a concurrent delivery, a stock report comparing against a number typed into the code instead of each product's own reorder level, and a category search that cannot express "this or that, but not those".

Requirements

Implement in app/queries.py:

  • restock(product, amount)
  • needs_reorder()
  • tools_or_paint()
  • paint_in_stock()
  • outside_garden()
  • promotable()

The following files are already implemented and provided: app/models.py, app/views.py and app/urls.py. Product holds sku (unique), name, category, quantity, reorder_level and discontinued, with Meta.ordering = ["sku"]; the categories in use are tools, paint, garden and safety. Every function in app/queries.py already has its name and its arguments; keep both. app/views.py serves one page at / that lists the products and what each read returns.

1. restock(product, amount)

  • Adds amount to the stored quantity of the product it is given, with the database doing the addition.
  • Exactly one query reaches the database, it is an UPDATE, and the new quantity is computed from the stored column rather than from a number carried in from Python. That rules out loading the row first and it rules out refreshing it afterwards; refreshing is the caller's business.
  • The caller hands over a Product instance it may have been holding for a while, so the quantity on that instance is not evidence of anything.
  • The race: P-100 is read at quantity 10 and handed over, a delivery of 5 is recorded against that row by someone else, then restock is called with 2. The row must end at 17. A read-modify-write ends at 12, because it adds 2 to the 10 it was carrying and the delivery of 5 is overwritten.

2. needs_reorder()

  • Returns the products whose quantity is at or below their own reorder_level, as one filtered query.
  • "At" counts: a product holding 5 units with a reorder level of 5 needs a reorder, and one holding 2 against a level of 1 does not. The comparison is column against column, so a product holding 40 against a level of 50 is in the result and one holding 12 against a level of 5 is not.
  • The WHERE clause of that one statement names both quantity and reorder_level, so the comparison happens in the database.

3. The four composed reads

  • tools_or_paint(): the category is tools or the category is paint.
  • paint_in_stock(): the category is paint and the quantity is above zero.
  • outside_garden(): the category is not garden, which leaves the safety products in alongside the others.
  • promotable(): the category is tools or paint, and the product is not discontinued.
  • Each returns a single filtered queryset: evaluating it costs one query and the database chooses the rows. Build them with Q objects; any arrangement of the same logic is fine.
  • Every one of these five reads returns a queryset its caller can narrow again with .filter(sku=...). A composed condition the database evaluates can still be narrowed by its caller; a list of the right objects cannot.
  • Ordering does not matter; the set of products does.

Notes

  • An F() is a reference to a column, resolved while the query runs, so update(quantity=F("quantity") + amount) never holds the number in Python and there is nothing to go stale. Re-reading the row just before the sum narrows the window; it does not close it.
  • An update() writes to the database and does not touch the Python object in hand, so the instance still shows the old number afterwards.
  • & binds tighter than | in Python, so the parentheses around an or-group are the rule rather than decoration: Q(a) | Q(b) & ~Q(c) reads "a, or b that is not c" and lets a c row through.
  • A Q object may share a filter() call with keyword arguments as long as every positional Q comes first.
  • Every read is one query with the comparison in it. Fetching the products and choosing between them in a Python loop or comprehension produces the right list but is not a filtered query.
  • This question needs no aggregate() or annotate(): every answer is a filter or an update.

More in ORM Aggregation & Annotation

See the module
Store Totals AggregateThe store metrics are built by pulling every order row into Python and adding the totals up in a loop. Replace that with one aggregate() call that returns revenue, average order value, order count and both extremes under defined names, with defined values for an empty store.50%1 of 2 solvedmediumPer-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 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.