select_related & prefetch_related (Django)
select_related and prefetch_related are Django ORM optimizations that fetch related objects efficiently to avoid the N+1 query problem. Use select_related for foreign keys/one-to-one and prefetch_related for many-to-many and reverse relations.
Django
Looping over objects and accessing a related field triggers a separate query per object — the N+1 problem (1 query for the list plus N for the relations). These methods eliminate the extra queries by fetching related data up front.
select_related performs a SQL JOIN to pull single-valued relations (ForeignKey, OneToOne) in the same query: Post.objects.select_related('author'). prefetch_related runs a second query and joins the results in Python, which is what multi-valued relations (ManyToMany, reverse ForeignKey) need: Author.objects.prefetch_related('post_set').
Choosing the right one matters: using select_related on a many-to-many would not work, and prefetching a simple foreign key is less efficient than a join. Spotting N+1 queries with the Django Debug Toolbar and fixing them here is a major performance win.
Syntax
qs.select_related("author")
qs.prefetch_related("tags")Examples
Python
# without optimization: 1 + N queries
for post in Post.objects.all():
print(post.author.name) # a query each loop
# with select_related: a single JOIN query
for post in Post.objects.select_related("author"):
print(post.author.name)
# many-valued relation needs prefetch_related
Author.objects.prefetch_related("post_set")