Skip to content

Django ORM prefetch_related Fix

DodaTech Updated 2026-06-24 1 min read

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

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.

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.
  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. 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

### Can I chain select_related and prefetch_related?

Yes. They serve different relation types and work together: Post.objects.select_related('author').prefetch_related('tags').all()

Yes. If your related model has a default ordering, prefetch_related respects it. You can override with a Prefetch object: Prefetch('comments', queryset=Comment.objects.order_by('-created_at'))

Every access to the relation hits the database. With 200 posts and 5 tags each, that's 201 queries instead of 2.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro