Junior — Middle
Explain the mechanism of the select_related method in Django and how it affects database query execution.
sobes.tech AI
Answer from AI
The select_related method in Django is used to optimize database queries when working with related models through ForeignKey or OneToOneField. It performs an SQL JOIN and loads related objects in a single query, reducing the number of database hits.
Without select_related, accessing a related object in Django will execute a separate query for each such object (lazy loading). With select_related, all data is fetched at once, significantly improving performance when retrieving related data.
Example:
# Without select_related
books = Book.objects.all()
for book in books:
print(book.author.name) # A separate query to author for each book
# With select_related
books = Book.objects.select_related('author').all()
for book in books:
print(book.author.name) # All data loaded in a single query
Thus, select_related reduces the number of queries and speeds up application performance when used correctly.