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

Single Object Retrieval

easy75%3 of 4 solved

Problem statement

The product detail page and the category summary need five small retrieval helpers, and app/queries.py only has empty stubs for them. The Product model, the JSON views and the URLs are provided. Your task is to implement the helpers so single objects are fetched safely: a lookup by the unique sku returns None instead of crashing when nothing matches, a lookup by the non-unique name refuses to guess when several products share it, the first product of a possibly empty category comes back as None rather than an error, and the existence and count checks never load product rows.

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) - False means the product is discontinued

Meta.ordering = ["sku"], so the default ordering of any Product queryset is by sku ascending.

Example rows:

skunamecategorypriceis_active
BLB-010LED Bulblighting3.99yes
LMP-200Desk Lamplighting24.50yes
STR-550LED Striplighting18.00yes
CHR-900Office Chairfurniture149.00yes

Requirements

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

  1. get_product_by_sku(sku) - return the active product whose sku equals sku exactly (case-sensitive). When there is none - an unknown sku, or a discontinued product (is_active=False) - return None; no exception may escape.
  2. get_product_by_name(name) - name is not unique. Return the single active product with exactly that name, or None when there is none. Discontinued products are ignored, so an active product and a discontinued one with the same name count as a single match. When more than one active product has that name, the function must raise Product.MultipleObjectsReturned to its caller: do not catch it and do not pick one of the matches.
  3. first_in_category(category) - return the product with the lowest sku in category, or None when the category has no products (no exception).
  4. category_has_products(category) - return True / False (a real bool). It must run exactly one query, and that query must be an existence check: it selects no Product columns, does not count rows, and stops at the first match (LIMIT 1).
  5. count_in_category(category) - return the number of products in category as an int. It must run exactly one query that counts in the database (COUNT) and selects no Product columns.

Only the two lookups (1 and 2) skip discontinued products; the category helpers (3 to 5) include every product in the category.

The provided endpoints use them:

MethodRouteResponse
GET/products/<sku>/200 {"sku", "name", "category", "price"} (price as a string, e.g. "24.50"); 404 {"error": "Product not found"} when get_product_by_sku returns None
GET/categories/<category>/summary/200 {"category", "count", "has_products", "first_sku"}; first_sku is null for an empty category
Sample Requests & Responses
GET /products/LMP-200/
200 {"sku": "LMP-200", "name": "Desk Lamp", "category": "lighting", "price": "24.50"}

GET /products/NOPE-000/ 404 {"error": "Product not found"}

GET /categories/lighting/summary/ 200 {"category": "lighting", "count": 3, "has_products": true, "first_sku": "BLB-010"}

GET /categories/garden/summary/ 200 {"category": "garden", "count": 0, "has_products": false, "first_sku": null}

>>> get_product_by_name("Office Chair")
<Product: CHR-900 - Office Chair>
>>> Product.objects.create(sku="CHR-901", name="Office Chair", category="furniture", price="99.00")
>>> get_product_by_name("Office Chair")
Traceback (most recent call last):
  ...
app.models.Product.MultipleObjectsReturned: get() returned more than one Product -- it returned 2!
>>> get_product_by_name("Bookshelf") is None
True
>>> Product.objects.create(sku="BLB-011", name="LED Bulb", category="lighting", price="2.99", is_active=False)
>>> get_product_by_sku("BLB-011") is None
True
>>> get_product_by_name("LED Bulb")
<Product: BLB-010 - LED Bulb>

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 solvedeasyCatalog Query ToolboxSupport needs one set of catalog answers they can trust. Build query functions for search, newest items, price lists, name lists and single lookups, each skipping inactive products and running exactly one query.100%3 of 3 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.