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

Dashboard Under Budget

mediumDjango ORMQuery Optimization—No data yet

Problem statement

In this Django project, implement the team dashboard inside a hard budget of six statements per render. Build the dashboard view in app/views.py so the chain to each member's department is joined on, the three collections are batched, the heavy column is never fetched, and the two facts above the table are answered by the database. The page it produces has to stay exactly as it is, down to the text of every element.

Requirements

Implement:

  • the dashboard view in app/views.py

The following files are already implemented and provided: app/models.py, app/urls.py and the template. Member holds name, slug, role, bio and a many-to-many tags, ordered by name; bio is the heavy column, a few kilobytes of text per row the dashboard never shows. Role holds a title and a department, so reaching a department from a member crosses two relations, and two roles share each department. Project points at a member and carries a status of Project.ACTIVE or Project.ARCHIVED. Activity points at a member and carries a summary and a happened_on date. Neither Project nor Activity declares a default ordering. /dashboard/ renders the read-only page, which reads members (in name order), has_archive, tag_total, and on each member member.active_projects and member.recent_activity. Those last two are not model attributes but names the view attaches, and the template renders a dash for a member whose list is empty.

1. The chain on the members' own statement

  • The statement that fetches the members also fetches each member's role and that role's department, so the department table is read once for the whole page rather than once per member.
  • The whole chain has to be named: the first hop alone leaves the second one lazy.

2. The three collections, batched

  • Each of the members' tags, active projects and activities is fetched for the whole page in one statement each, so each of those tables is read exactly once however many members there are.
  • The projects arrive filtered and ordered by the database: only Project.ACTIVE rows, by name, published on each member as active_projects. The archived rows are never handed back, so a statement that fetches every project and drops the archived ones afterwards is not an answer here.
  • The activities arrive newest first, published on each member as recent_activity, so the head of that list is the member's latest activity.
  • Reading the loaded collections costs no further queries.

3. The heavy column stays in the database

  • The members' statement asks for name, slug and the role foreign key, plus the primary key, and does not ask for bio.
  • bio stays deferred: nothing in the view and nothing the page renders reads it, because reading it would cost one query per member and undo the trim.

4. The two facts, answered by the database

  • has_archive comes from a statement that stops at the first match and fetches no project columns, and is false when nothing is archived.
  • tag_total comes from a statement that counts in the database and fetches no tag columns, and grows by one when one more tag is defined.

5. The budget

  • One full request, template rendering included, costs six statements: the members with their role and department joined on, plus one each for the tags, the active projects and the activities, plus one for the archive flag and one for the tag count.
  • That total does not grow with the number of members or with the size of any collection. Fifteen more members, or twelve more projects on one member, still cost six.

6. The page is unchanged

  • The page is compared element by element. Every element inside <div id="dashboard"> that carries an id - the archive note, the tag total, and each member row's name, role, department, tags, projects and activity cell - holds exactly the text the seeded data implies, and the rows are the same rows in the same order.
  • The template is read-only, so the markup around those elements cannot move; what stays identical is the text in them.

Notes

  • Keep the five context and attribute names exactly as they are: the template reads them.
  • select_related joins a chain of foreign keys into the statement you already run; prefetch_related runs one extra statement per collection and matches the rows up in Python, however many rows there are.
  • Prefetch takes the queryset to fetch with and to_attr to publish it as. member.active_projects is then loaded, while member.projects.all() is still a fresh query. Filtering in Python instead renders the same page, but the database still hands over rows nobody wanted.
  • only and defer produce the same SELECT when the only column to drop is the heavy one, and either is a correct way to get there. A trimmed row is still a real model instance, and get_deferred_fields() shows which columns it is missing.
  • bool(list(qs)) and len(list(qs)) answer the flag and the total by shipping every matching row to Python and then throwing the rows away; exists() and count() ask the database.
  • A QuerySet caches its rows once it has been iterated, so a second pass over one is free and proves nothing - measure a fresh request. And a Python loop over .all() is one statement too, so a low count on its own never proves the database did the filtering.
  • Build every answer out of QuerySet methods. No raw SQL, no caching, nothing from outside requirements.txt.

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 yetmediumPrefetch Related CollectionsA course listing reads each course's tags and students one course at a time, and its filtered student list re-queries on every row. Batch both collections with prefetch_related and apply the filter and the ordering through a Prefetch object.—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 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.