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_relatedorprefetch_related, multiple additional database queries occur.- Solution: Use
select_relatedfor ForeignKey and OneToOne,prefetch_relatedfor ManyToMany and reverse relations.
- Solution: Use
-
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.
- Solution: Apply filtering (
-
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().
- Solution: Save results to a list or use
-
Lack of indexes: Slow queries due to missing indexes on frequently filtered fields.
- Solution: Add indexes via
db_index=Truein models.
- Solution: Add indexes via
-
Incorrect use of transactions: Missing or improper transaction management can lead to data inconsistency.
- Solution: Use
transaction.atomic()to group operations.
- Solution: Use
-
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