Community Question Bundle

Django ORM N+1 and prefetch_related Drill

Four questions on Django ORM patterns I keep flagging in code review: spotting N+1 in templates, choosing select_related vs prefetch_related, slicing prefetches, and avoiding the .count() trap.

Django ORM N+1 and prefetch_related Drill

Four questions on Django ORM patterns I keep flagging in code review: spotting N+1 in templates, choosing select_related vs prefetch_related, slicing prefetches, and avoiding the .count() trap.

Question Bundle
Python
4 questions
framework
database
query-optimization
interview-prep
freyadiallo

By @freyadiallo

April 16, 2026

·

Updated May 20, 2026

412 views

14

4.4 (9)

A Django template renders {% for order in orders %}{{ order.customer.name }}{% endfor %} and the page hits the DB 41 times for 40 orders. What is the smallest change to the queryset to fix it, and why is it select_related rather than prefetch_related?

Trace it

Trace it with django.db.connection.queries. Order.objects.all() followed by {{ order.customer.name }} in a template across 40 orders runs 41 queries: one for the list, then one per order.customer access. Switch to Order.objects.select_related('customer').all() and you get 1 query with a JOIN.