Junior — Middle
Can you explain what a Prefetch object in Django is and how it is used to optimize database queries?
sobes.tech AI
Answer from AI
In Django, the Prefetch class object is used to optimize database queries when working with "many-to-many" or "reverse relations". It allows explicitly specifying which related objects to prefetch, as well as applying additional filters or modifying the queryset.
This helps avoid the "N+1 queries" problem, where a separate database query is made for related objects for each main object.
Example of usage:
from django.db.models import Prefetch
# Suppose we have models Author and Book, where Author has a many-to-many relation with Book
books_qs = Book.objects.filter(published=True)
authors = Author.objects.prefetch_related(Prefetch('books', queryset=books_qs))
for author in authors:
# Here, author.books.all() will already contain only published books, loaded in a single query
for book in author.books.all():
print(book.title)
Thus, Prefetch allows controlling which related data is loaded and how, improving application performance.