Query Performance / N+1 (Django)
Query performance in Django is mostly about reducing the number of database queries. The classic pitfall is the N+1 problem, where iterating objects fires one extra query per related access; fixes include select_related and only().
Django
Most Django performance issues are query-count issues, not slow individual queries. The N+1 problem is the prime example: a list view loads N objects, then accessing a related field inside the template loop triggers N more queries. The Django Debug Toolbar makes these visible.
Key tools: select_related/prefetch_related to fetch relations efficiently; only()/defer() to load just the columns you need; values()/values_list() to skip building full model instances; exists() instead of len() for presence checks; and database indexes (db_index=True or Meta.indexes) on columns you filter and order by.
Also beware of evaluating a QuerySet repeatedly (cache it in a variable), and of count() vs len() — len() loads all rows while count() runs a COUNT in the database. Measuring before optimizing is essential.
Syntax
qs.select_related(...).only("a", "b")Examples
Python
# load only needed columns and the related author in one query
posts = (Post.objects
.select_related("author")
.only("title", "author__name"))
# COUNT in the DB instead of loading rows
total = Post.objects.filter(published=True).count()