Django ORM prefetch_related Fix
In this tutorial, you'll learn about Django ORM prefetch_related Fix. We cover key concepts, practical examples, and best practices.
The Problem
Fetching ManyToMany fields or reverse ForeignKey relations in a loop generates one query per object. With 100 blog posts, accessing each post's tags produces 101 queries instead of 2.
Quick Fix
Wrong — N+1 on ManyToMany
class Post(models.Model):
tags = models.ManyToManyField(Tag)
posts = Post.objects.all()
for post in posts:
print([t.name for t in post.tags.all()])
Output: 1 query for posts + N queries for tags
Correct — prefetch_related
posts = Post.objects.prefetch_related('tags').all()
for post in posts:
print([t.name for t in post.tags.all()])
Output: 2 queries total — one for posts, one for all tag relations.
Reverse FK with prefetch_related
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
posts = Post.objects.prefetch_related('comment_set').all()
for post in posts:
print([c.text for c in post.comment_set.all()])
Custom Prefetch objects
from django.db.models import Prefetch
recent = Comment.objects.filter(created_at__gt=one_day_ago)
posts = Post.objects.prefetch_related(
Prefetch('comment_set', queryset=recent)
).all()
Prevention
- Treat any loop accessing a relation as a red flag.
- Use Prefetch objects to filter prefetched data without extra queries.
- Test query counts with
assertNumQueries.
Common Mistakes with orm prefetch related
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world DJANGO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro