Sobes.tech
Junior — Middle

What common mistakes can occur when working with Django ORM and how to avoid them?

sobes.tech AI

Answer from AI

Common mistakes when working with Django ORM and how to avoid them:

  • N+1 queries: When fetching related objects without using select_related or prefetch_related, multiple additional database queries occur.

    • Solution: Use select_related for ForeignKey and OneToOne, prefetch_related for ManyToMany and reverse relations.
  • Inefficient queries: Using .all() and filtering in Python instead of filtering at the database level.

    • Solution: Apply filtering (filter, exclude) and aggregation methods at the ORM level.
  • Modifying QuerySet during iteration: Changing the QuerySet or related objects while iterating can lead to errors.

    • Solution: Save results to a list or use .iterator().
  • Lack of indexes: Slow queries due to missing indexes on frequently filtered fields.

    • Solution: Add indexes via db_index=True in models.
  • Incorrect use of transactions: Missing or improper transaction management can lead to data inconsistency.

    • Solution: Use transaction.atomic() to group operations.
  • Ignoring migration errors: Mismatch between models and database.

    • Solution: Always create and apply migrations after model changes.

Example of using select_related to avoid N+1:

# Without select_related
books = Book.objects.all()
for book in books:
    print(book.author.name)  # Separate query for each author

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