StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 12 · Query Optimization

Prefetch Related Collections

mediumDjango ORMQuery Optimization—No data yet

Problem statement

In this Django project, implement the course listing inside a three-query budget. Build the queryset in CourseListView.get_queryset in app/views.py so each course's tags arrive in one extra query and its active students arrive in another, filtered and ordered inside that query. Today every course asks the database for its own tags, and the student list has no active_enrolments to loop over at all, so it renders nothing.

Requirements

Implement:

  • CourseListView.get_queryset in app/views.py

The following files are already implemented and provided: app/models.py, app/urls.py and the template. Course holds title, slug and tags, a many-to-many to Tag. Enrolment points at a course through a foreign key with related_name="enrolments" and carries student_name, joined_on and a status that is Enrolment.ACTIVE or Enrolment.DROPPED; it declares no Meta.ordering, so its rows arrive in whatever order the database offers. /courses/ is routed to CourseListView.as_view(), and the page loops over courses, then over course.tags.all for the tag list and over course.active_enrolments for the student list. CourseListView already knows its model, its template and its context name.

1. GET /courses/ - both collections batched

  • Purpose: List every course with its tags and its active students.
  • Response:
  • 200 OK: every course in the catalog, each with its own tag list and its own student list. A course whose enrolments are all dropped shows an empty student list, and a course with no tags and no enrolments at all still appears in the listing.
  • One full render costs exactly three queries - one for the courses, one for the tags, one for the enrolments - and that count holds when the catalog grows.

2. The filtered, ordered student list

  • The student list shows only enrolments whose status is Enrolment.ACTIVE, sorted by student_name ascending.
  • Both the filter and the ordering are applied inside a Prefetch object for the enrolments relation, so they happen in that one extra query rather than once per course.
  • The result is published as to_attr="active_enrolments", so the page can loop over course.active_enrolments. A course with no active enrolment gets an empty list, not a missing attribute.
  • The tests re-execute the captured statement and compare the delivered rows and their order against what the filter should have returned, so filtering in Python renders the same page and still fails.

3. Read the collections as they are

  • Reading the prefetched tags and the prefetched student list costs no further queries.
  • Do not call .filter() or .order_by() on a course's collection after the fetch, and do not loop over the courses to fetch their rows one at a time.

Notes

  • select_related cannot help with a collection: a join that multiplies rows cannot fill a list. prefetch_related runs one extra query per collection, collects every related row for the whole page at once, and hands each parent its share in Python - one query for the rows plus one per prefetched collection, whatever the row count.
  • Without to_attr, the filtered rows replace what course.enrolments.all() returns, which surprises anyone who expects the whole collection there.
  • The prefetch cache answers course.tags.all() for free, but course.tags.filter(...) and course.tags.order_by(...) are new questions and go back to the database once per course. Ask for the shape you want in the Prefetch and read it as it is.
  • Filter the prefetched enrolments, not the course queryset: narrowing Course.objects by enrolments__status drops courses and duplicates rows.
  • Build the queryset in get_queryset (or as the view's queryset attribute); do not fetch rows in the template and do not paginate.
  • Leave home, the template, the models and the URL map as they are.

More in Query Optimization

See the module
Select Related Detail PageThe order history page fetches the orders in one query and then fires another query per row for the customer, and another for that customer's region. Collapse the whole chain into the page's one-query budget with select_related, leaving every rendered row exactly as it was.—No data yetmediumLean Field LoadingThe exports page loads every article's full body just to list titles, and it works out its flag and its total by pulling all the rows into Python. Trim the query to the columns the page shows and let the database answer the two questions instead.—No data yetmediumDashboard Under BudgetThe team dashboard renders correctly and costs hundreds of queries: the members arrive alone, then every row fetches its role, that role's department, its tags, its projects and its activities one at a time. Rebuild the page's data layer so the same markup renders inside a six query budget, combining a chained join, three batched collections with a filtered Prefetch, a trimmed column list and an existence check.—No data yetmedium

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.