StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 2 · QuerySets & ORM Basics

Catalog Query Toolbox

easy100%3 of 3 solved

Problem statement

Support needs one search endpoint over the catalog that answers real questions - matching, ranges, ordering, top-N, shaped reports, single-product lookups, counts and existence. The Product model, the GET /catalog/search/ view and the URL are provided; the nine query functions behind them in app/queries.py are empty stubs. Your task is to implement them by combining what the practice problems covered: filters and field lookups, excluding inactive products, ordering and slicing, shaping rows into dicts or plain values, and safe single-object retrieval. Every function answers with exactly one database query.

Existing Model

app/models.py defines Product (provided, do not change it):

FieldType
skuCharField(max_length=20, unique=True)
nameCharField(max_length=100) - NOT unique
categoryCharField(max_length=50)
priceDecimalField(max_digits=10, decimal_places=2)
is_activeBooleanField(default=True)
created_atDateTimeField()

Meta.ordering = ["sku"] is only the model default. Every question below defines its own order, so do not rely on it.

Example rows:

skunamecategorypriceis_active
CB-999USB-C Cableaccessories9.99yes
SL-025LAPTOP SLEEVEaccessories25.00yes
MS-025Wireless Mouseaccessories25.00yes
MP-005Mouse Padaccessories5.00no
LP-240Desk Lamplighting24.50yes
LP-310Desk Lamplighting31.00yes

Requirements

Implement every function in app/queries.py. The view in app/views.py already calls them.

Rules that apply to every function:

  • Inactive products do not exist for any question. Exclude every product with is_active=False - from lists, shaped rows, single-object lookups, counts and existence checks alike.
  • One query per answer. Calling a function and, when it returns a queryset, evaluating that queryset runs exactly one database query in total. Do all filtering, ordering, slicing and shaping in the database - never load rows and filter or sort them in Python.
  • Functions that return several rows return a Django QuerySet (not a list).
  • A category argument matches the stored category exactly (case-sensitive): "Lighting" is not "lighting".
#FunctionAnswer
1search(name=None, min_price=None, max_price=None)QuerySet of active products. name matches when it is contained anywhere in the product name, ignoring case. min_price / max_price are inclusive bounds. Arguments that are None apply no filter; given arguments intersect. Ordered by price ascending, then name ascending.
2newest(n)QuerySet of the n most recently created active products: created_at descending, then name ascending, exactly n rows (fewer only when there are fewer active products - then all of them).
3price_list(category)QuerySet of plain dicts with exactly the keys sku, name, price for the active products in category, ordered by price descending, then name ascending.
4names_in_category(category)QuerySet of plain name strings (not tuples, not dicts) for the active products in category, ordered by name ascending. Duplicate names appear once per product.
5get_by_sku(sku)The active product whose sku equals sku exactly (case-sensitive). When there is none - unknown sku or an inactive product - return None; no exception may escape.
6get_by_name(name)The single active product whose name equals name exactly; None when there is none. When more than one active product has that name, raise Product.MultipleObjectsReturned to the caller - do not catch it and do not pick one.
7cheapest_in_category(category)The active product in category with the lowest price (ties: name ascending); None when the category has no active products.
8category_has_products(category)True / False (a real bool): does category have at least one active product? The query must be an existence check: it selects no Product columns, does not count rows, and stops at the first match (LIMIT 1).
9count_in_category(category)The number of active products in category as an int, from one query that counts in the database (COUNT) and selects no Product columns.

The provided endpoint uses them:

MethodRouteQuery parametersResponse
GET/catalog/search/?question=searchname, min_price, max_price (blank = not given)200 {"results": [product, ...]}
GET/catalog/search/?question=newestn (default 5)200 {"results": [product, ...]}
GET/catalog/search/?question=price_listcategory200 {"results": [{"sku", "name", "price"}, ...]}
GET/catalog/search/?question=namescategory200 {"results": ["name", ...]}
GET/catalog/search/?question=productsku200 product; 404 {"error": "Product not found"} when get_by_sku returns None
GET/catalog/search/?question=summarycategory200 {"category", "count", "has_products", "cheapest_sku"}; cheapest_sku is null when there is no active product

A product is {"sku", "name", "category", "price"} with price as a string, e.g. "24.50". Any other question answers 400 {"error": "Unknown question"}.

Sample Requests & Responses

With the example rows above loaded:

GET /catalog/search/?question=search&max_price=25
200 {"results": [
  {"sku": "CB-999", "name": "USB-C Cable", "category": "accessories", "price": "9.99"},
  {"sku": "LP-240", "name": "Desk Lamp", "category": "lighting", "price": "24.50"},
  {"sku": "SL-025", "name": "LAPTOP SLEEVE", "category": "accessories", "price": "25.00"},
  {"sku": "MS-025", "name": "Wireless Mouse", "category": "accessories", "price": "25.00"}
]}

GET /catalog/search/?question=search&name=mouse 200 {"results": [{"sku": "MS-025", "name": "Wireless Mouse", "category": "accessories", "price": "25.00"}]}

GET /catalog/search/?question=price_list&category=accessories 200 {"results": [ {"sku": "SL-025", "name": "LAPTOP SLEEVE", "price": "25.00"}, {"sku": "MS-025", "name": "Wireless Mouse", "price": "25.00"}, {"sku": "CB-999", "name": "USB-C Cable", "price": "9.99"} ]}

GET /catalog/search/?question=names&category=lighting 200 {"results": ["Desk Lamp", "Desk Lamp"]}

GET /catalog/search/?question=product&sku=MP-005 404 {"error": "Product not found"}

GET /catalog/search/?question=summary&category=accessories 200 {"category": "accessories", "count": 3, "has_products": true, "cheapest_sku": "CB-999"}

GET /catalog/search/?question=summary&category=garden 200 {"category": "garden", "count": 0, "has_products": false, "cheapest_sku": null}

>>> get_by_name("Wireless Mouse")
<Product: MS-025 - Wireless Mouse>
>>> get_by_name("Desk Lamp")
Traceback (most recent call last):
  ...
app.models.Product.MultipleObjectsReturned: get() returned more than one Product -- it returned 2!
>>> get_by_name("Mouse Pad") is None
True
>>> list(names_in_category("accessories"))
['LAPTOP SLEEVE', 'USB-C Cable', 'Wireless Mouse']

More in QuerySets & ORM Basics

See the module
Filtered Product LookupsThe product search returns everything no matter what the user asks for. Filter products by a case-insensitive name match and an inclusive price range, leave out inactive items, sort by price then name, and answer in a single database query.100%5 of 5 solvedeasyOrdered Result ShapingA report needs items in the right order, only a few columns, and just the latest rows. Add chainable QuerySet methods that sort by name or newest first, take the top N, and return plain dicts or a flat list of names.100%4 of 4 solvedeasySingle Object RetrievalDetail lookups crash on unknown products and silently pick a random row when names repeat. Fetch single products safely by sku and by name, ignore discontinued items, and answer "any products?" and "how many?" without loading rows.75%3 of 4 solvedeasy

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.