How can the number of accesses to a related table be reduced when executing queries?
sobes.tech AI
Answer from AI
To reduce the number of queries to the related table when executing queries in Python (for example, when working with ORM such as Django ORM or SQLAlchemy), optimization techniques for loading related data are used:
-
Eager loading — pre-load related objects with a single query using
select_related(Django) orjoinedload(SQLAlchemy). This reduces the number of individual queries. -
Prefetching — load related objects with a separate query in advance to avoid N+1 problems. In Django, this is
prefetch_related. -
Caching — store query results in memory or external cache to avoid repeated database access.
Example with Django ORM:
# Without optimization: a separate query to the related table for each object
books = Book.objects.all()
for book in books:
print(book.author.name) # will trigger a separate query for each author
# With optimization:
books = Book.objects.select_related('author').all()
for book in books:
print(book.author.name) # all data loaded with a single query
Thus, using select_related and prefetch_related can significantly reduce the number of database queries and improve performance.