22
My Django application is slow. Database queries are taking forever. How can I optimize my ORM queries?
Loading...
Q&A · Answered
My Django application is slow. Database queries are taking forever. How can I optimize my ORM queries?
Accepted answer
Django ORM optimization is crucial for performance. Here are the key techniques:
# Bad: N+1 queries
for book in Book.objects.all():
print(book.author.name)
# Good: One query with JOIN
books = Book.objects.select_related('author')
for book in books:
print(book.author.name)
# For many-to-many relationships
books = Book.objects.prefetch_related('tags')
# Only fetch needed fields
users = User.objects.only('id', 'username')
# Defer heavy fields
articles = Article.objects.defer('content')
class Article(models.Model):
title = models.CharField(max_length=200)
class Meta:
indexes = [
models.Index(fields=['title']),
]Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.