Skip to content

Q&A · Answered

How to optimize Django ORM queries for better performance

asked 9 months, 1 week ago 563 views 1 answer
22

My Django application is slow. Database queries are taking forever. How can I optimize my ORM queries?

1 Answer

One accepted
26

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago

Django ORM optimization is crucial for performance. Here are the key techniques:

Use select_related and prefetch_related

# 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')

Use only() and defer()

# Only fetch needed fields
users = User.objects.only('id', 'username')

# Defer heavy fields
articles = Article.objects.defer('content')

Use database indexes

class Article(models.Model):
    title = models.CharField(max_length=200)
    
    class Meta:
        indexes = [
            models.Index(fields=['title']),
        ]

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.