Skip to main content
Django Bug Hunt Hard +35 XP

N+1 Query Problem

This view makes too many database queries.

DjangoFind the bug
1def post_list(request):
2 posts = Post.objects.all()
3 return render(request, 'list.html', {'posts': posts})
4# template: {% for post in posts %}{{ post.author.name }}{% endfor %}
The bug is on line 2

Select the correct fix

Show answer and explanation

Answer: Use select_related('author') in the queryset

Accessing post.author in a loop triggers one query per post. select_related('author') fetches all authors in one JOIN query.

Hint: One query per post = N+1 problem.

What this challenge tests

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

Related challenges