Sobes.tech
Junior — Middle

What methods can be used to avoid the N+1 problem when working with related models in Django?

sobes.tech AI

Answer from AI

The N+1 problem occurs when, during the retrieval of related models in Django, a separate database query is executed for each main record, which significantly reduces performance.

To avoid this problem, the following methods are used:

  • select_related() — for eager loading of related objects via SQL JOIN. Works for ForeignKey and OneToOne fields.

  • prefetch_related() — for prefetching related objects with a separate query and then combining them in Python. Suitable for ManyToMany and reverse relations.

Example:

# Without optimization
books = Book.objects.all()
for book in books:
    print(book.author.name)  # For each book, a separate query to author

# Using select_related
books = Book.objects.select_related('author').all()
for book in books:
    print(book.author.name)  # One query with JOIN

Using these methods significantly reduces the number of queries and improves performance.