Junior — Middle
What methods have you used to improve query efficiency in Django?
sobes.tech AI
Answer from AI
To improve query efficiency in Django, I used the following methods:
-
select_related() — for eager loading related objects through foreign keys, reducing the number of SQL queries.
-
prefetch_related() — for preloading related objects, especially when working with many-to-many relationships.
-
values() and values_list() — for selecting only the necessary fields, which reduces the amount of data transferred.
-
annotate() and aggregate() — for performing calculations at the database level, reducing the load on Python.
-
Using indexes — adding indexes on fields that are frequently filtered or sorted.
-
Caching — applying caching of query results using Django's cache framework.
Example of using select_related():
# Without select_related: will result in N+1 queries
books = Book.objects.all()
for book in books:
print(book.author.name)
# With select_related: one join query
books = Book.objects.select_related('author').all()
for book in books:
print(book.author.name)