Junior — Middle
What methods do you use to improve the performance of queries related to models and their relationships?
sobes.tech AI
Answer from AI
To improve the performance of queries related to models and their relations, the following methods are often used:
-
Eager loading: preloading related objects to avoid N+1 query problem. In Django, this is done using
select_relatedfor ForeignKey relations andprefetch_relatedfor ManyToMany relations. -
Query optimization: using ORM methods to fetch only necessary fields (
only(),values()) to reduce data transfer. -
Database indexing: creating indexes on fields that are frequently used in filters or joins.
-
Caching: storing results of heavy queries in cache (e.g., Redis) for reuse.
Example with Django ORM:
# Eager loading related models
queryset = Book.objects.select_related('author').all()
# Fetching only needed fields
queryset = Book.objects.only('title', 'author__name')
This reduces the number of database queries and speeds up application performance.