Skip to main content
Django Bug Hunt Hard +35 XP

N+1 Query

This view runs 1 + N queries for N posts.

DjangoFind the bug
1posts = Post.objects.all()
2for post in posts:
3 print(post.author.name)
The bug is on line 1

Select the correct fix

Show answer and explanation

Answer: Use select_related('author') on queryset

Each post.author access hits the DB. select_related does a SQL JOIN and fetches everything in one query.

Hint: select_related reduces DB queries for foreign keys.

What this challenge tests

Bug Hunt in Django: performance, orm, n+1.

Related challenges