Middle
When making requests with related models in Django ORM, how do you avoid unnecessary SQL queries? What two ORM mechanisms do you know?
sobes.tech AI
Answer from AI
In Django ORM, two main mechanisms are used to avoid unnecessary SQL queries when working with related models:
-
select_related — performs an SQL JOIN and loads related objects in the same query. It works for ForeignKey and OneToOne fields.
-
prefetch_related — performs a separate query for related objects and links them in Python. Suitable for ManyToMany and reverse relations.
Example:
# Without optimization
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) # one query with JOIN
# With prefetch_related for ManyToMany
books = Book.objects.prefetch_related('tags').all()
for book in books:
for tag in book.tags.all():
print(tag.name)
Using these methods significantly reduces the number of queries and improves performance.