Thursday 10:30 a.m.–11 a.m.

Optimizing your webapp by using django-debug-toolbar, select_related(), and prefetch_related().

Christopher Adams

Audience level:



This talk explains how to perform SQL query analysis and how to rewrite your views to reduce the number of queries Django uses in evaluating your model objects and their attributes. Special emphasis will be given to the powerful methods "select_related" and "prefetch_related." I will highlight the problem with a naive use of the ORM, how to target code for optimization, and the beneficial result.


Like any abstraction layer, the Django ORM hides the messy details about its underlying implementation. This is both the benefit and the risk. If used naively, any tool can cause unexpected or problematic outcomes. Likewise, the ORM can cause your application to interact with the database in an ugly and inefficient way, creating special challenges regarding scaling a quickly-prototyped webapp.

Many design patterns and best practices have been developed as a result to nudge developers to use the ORM more efficiently. The good news is, one of the easiest and most powerful patterns has been wrapped into Django itself, in the dual pairs of methods in the Django ORM's Queryset API, "select_related" and "prefetch_related." These methods instruct the Queryset, when evaluated, to perform two kinds of useful optimizations for you that can reduce the number of queries by orders of magnitude resulting from iterating over model objects and many-to-many relations.

This talk summarizes the problem these methods of the Queryset API try to solve, how to effectively use them, and the beneficial result. Mastering how to use Queryset methods efficiently and powerfully is a major step in moving from a beginner to intermediate Django developer.