Performance: Prefetch_related for reverse relations
This affects database query efficiency and page load speed by reducing the number of queries needed to fetch related data.
Jump into concepts and practice - no test required
authors = Author.objects.prefetch_related('book_set').all() for author in authors: print(author.book_set.all())
authors = Author.objects.all() for author in authors: print(author.book_set.all())
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Without prefetch_related (N+1 queries) | Minimal DOM impact | Minimal | Minimal | [X] Bad - slow data fetching delays rendering |
| With prefetch_related (2 queries) | Minimal DOM impact | Minimal | Minimal | [OK] Good - fast data fetching improves LCP |
prefetch_related with reverse relations in Django?prefetch_related doesprefetch_related fetches related objects in a separate query but combines results in Python to reduce database hits.prefetch_related on reverse relations loads all related objects efficiently, avoiding queries inside loops.comments on a Post model?prefetch_related, not prefetch or select_related for reverse relations.'comments' is correct, not a variable without quotes.class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
author = models.ForeignKey(Author, related_name='books', on_delete=models.CASCADE)
title = models.CharField(max_length=100)authors = Author.objects.prefetch_related('books')
for author in authors:
print(author.name, [book.title for book in author.books.all()])Author has many Book objects accessible via the reverse relation books.prefetch_related('books') loads all books for all authors in one extra query, so no queries happen inside the loop.posts = Post.objects.prefetch_related('comment_set')
for post in posts:
print(post.title, [c.text for c in post.comment_set.all()])Comment model has a ForeignKey to Post without a related_name set.related_name is set on a ForeignKey, Django uses modelname_set as the reverse relation name, here comment_set.prefetch_related('comment_set') and accessing post.comment_set.all() is correct and will work without error.Author objects with their Book objects, but only books published after 2020. How do you use prefetch_related for this filtered reverse relation?authors = Author.objects.prefetch_related( ... )
prefetch_related, use the Prefetch object with a filtered queryset.Prefetch('books', queryset=Book.objects.filter(pub_year__gt=2020)) inside prefetch_related() to load only books after 2020.