0
0
Djangoframework~5 mins

Prefetch_related for reverse relations in Django

Choose your learning style9 modes available
Introduction

Prefetch_related helps you get related data from the database in one go. For reverse relations, it fetches all related objects efficiently, so your app runs faster and uses fewer database queries.

You want to show a list of authors with all their books without extra database hits.
You need to display categories with all products in each category on a page.
You want to load all comments for a blog post efficiently.
You are building an admin panel showing users and their orders together.
Syntax
Django
Model.objects.prefetch_related('reverse_relation_name')
Use the name of the reverse relation as defined by related_name or the default modelname_set.
Prefetch_related works well for many-to-many and one-to-many reverse relations.
Examples
Fetch all authors and their books using the default reverse relation name book_set.
Django
authors = Author.objects.prefetch_related('book_set')
Fetch categories and all related products using a custom related_name='products'.
Django
categories = Category.objects.prefetch_related('products')
Load posts with all their comments efficiently.
Django
posts = Post.objects.prefetch_related('comments')
Sample Program

This example defines two models: Author and Book. Each Book links to an Author. We use prefetch_related('book_set') to get all books for each author in one database query. Then we print each author and their books.

Django
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

# Usage in a view or script
authors = Author.objects.prefetch_related('book_set')
for author in authors:
    print(f"Author: {author.name}")
    for book in author.book_set.all():
        print(f" - Book: {book.title}")
OutputSuccess
Important Notes

Always use prefetch_related for reverse relations to avoid many database queries inside loops.

If you set related_name on the ForeignKey, use that name instead of the default modelname_set.

Prefetch_related returns a queryset that you can iterate over just like normal querysets.

Summary

Prefetch_related fetches reverse related objects efficiently.

Use the reverse relation name to prefetch related data in one query.

This improves performance by reducing database hits in loops.