Junior — Middle
What is the purpose of using prefetch_related in ORM for query optimization?
sobes.tech AI
Answer from AI
prefetch_related is used in ORM (for example, Django ORM) to optimize queries when working with related objects.
Without prefetch_related, accessing related objects may trigger a separate database query for each object (the "N+1 queries" problem).
prefetch_related preloads related objects with an additional query and links them in memory, significantly reducing the number of queries and improving performance.
Example:
# Without prefetch_related
books = Author.objects.all()
for author in books:
print(author.book_set.all()) # Executes a separate query for each book
# With prefetch_related
authors = Author.objects.prefetch_related('book_set').all()
for author in authors:
print(author.book_set.all()) # All books are loaded with a single query