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

Ordered Result Shaping

easy100%4 of 4 solved

Problem statement

A report needs the newest items first, only two columns, and just the top five. The Item model is provided in app/models.py together with a custom ItemQuerySet whose five methods are empty stubs. Your task is to implement those methods so the database orders the items (including descending order with a tie-break), slices the top N, and returns rows shaped as plain dicts or as a flat list of names.

Sample Data

app/models.py already defines the model. It has no Meta.ordering, so an unordered query comes back in no guaranteed order:

FieldType
nameCharField(max_length=200)
priceDecimalField(max_digits=10, decimal_places=2)
created_atDateTimeField() (set explicitly on create)

Item.objects is an ItemQuerySet manager, so every method below is callable as Item.objects.<method>(). The examples in this README use these rows:

namepricecreated_at
Lamp25.002024-03-03 12:00
Desk180.002024-03-07 12:00
Chair95.502024-03-01 12:00
Rug60.002024-03-05 12:00
Mirror40.002024-03-02 12:00
Vase15.252024-03-06 12:00
Bench120.002024-03-04 12:00

Requirements

Implement the five stubbed methods of ItemQuerySet in app/models.py, at the # Write your code here markers.

How custom QuerySet methods work

ItemQuerySet is a subclass of Django's QuerySet, and objects = ItemQuerySet.as_manager() exposes every method you write on Item.objects, so Item.objects.newest_first() works. Inside a method, self is the queryset the method was called on - which may already be filtered, e.g. Item.objects.filter(price__gte=50).newest_first(). So each method must build on self (and may call its sibling methods, such as self.newest_first()), never start again from Item.objects, or the earlier filter is silently lost.

Rules for every method

  • It returns a Django QuerySet (not a list), so it can be chained and further filtered.
  • All ordering, slicing and shaping happen in the database - not by sorting or slicing a Python list.
  • It keeps any filter already applied to the queryset it was called on.
  • Do not add Meta.ordering to the model; each method applies its own ordering.

Methods

  1. alphabetical() - Item instances ordered by name A to Z.
  2. newest_first() - Item instances ordered by created_at, newest first. Items with the same created_at are ordered by name A to Z.
  3. top(n) - the first n items of newest_first(), as Item instances. When there are fewer than n items, all of them are returned (still newest first).
  4. report(n=5) - the first n items of newest_first() (default five), each row a plain dict with only the keys name and price. When there are fewer than n items, all of them are returned.
  5. names() - every item's name in newest_first() order, as plain strings (a flat, single-column result - not tuples, not dicts).
Sample Usage
>>> [i.name for i in Item.objects.alphabetical()]
['Bench', 'Chair', 'Desk', 'Lamp', 'Mirror', 'Rug', 'Vase']

>>> [i.name for i in Item.objects.newest_first()] ['Desk', 'Vase', 'Rug', 'Bench', 'Lamp', 'Mirror', 'Chair']

>>> [i.name for i in Item.objects.top(3)] ['Desk', 'Vase', 'Rug']

>>> list(Item.objects.report()) [{'name': 'Desk', 'price': Decimal('180.00')}, {'name': 'Vase', 'price': Decimal('15.25')}, {'name': 'Rug', 'price': Decimal('60.00')}, {'name': 'Bench', 'price': Decimal('120.00')}, {'name': 'Lamp', 'price': Decimal('25.00')}]

>>> list(Item.objects.report(2)) [{'name': 'Desk', 'price': Decimal('180.00')}, {'name': 'Vase', 'price': Decimal('15.25')}]

>>> list(Item.objects.names()) ['Desk', 'Vase', 'Rug', 'Bench', 'Lamp', 'Mirror', 'Chair']

If two more items, Easel and Clock, are also created on 2024-03-07 12:00, newest_first() starts with Clock, Desk, Easel.

>>> [i.name for i in Item.objects.top(20)]
['Desk', 'Vase', 'Rug', 'Bench', 'Lamp', 'Mirror', 'Chair']

>>> list(Item.objects.filter(price__gte=60).names()) ['Desk', 'Rug', 'Bench', 'Chair']

>>> [i.name for i in Item.objects.filter(price__lt=50).top(2)] ['Vase', 'Lamp']

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 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 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.