Skip to content

Five Django ORM Patterns That Slow Your Pages Down

Slow Django pages are almost always a database problem, not a server problem. These five ORM patterns show up in nearly every codebase I've worked on, and each one is straightforward to fix.

MI

mubashar

· 1 min read
Share

Before you add caching, increase your server spec, or look at CDN configuration, check your database queries. Slow Django pages are almost always an ORM problem. Django Debug Toolbar will show you exactly how many queries each page makes and how long each one takes.

1. The N+1 Query Problem

This is the most common one. You query for 20 blog posts, then inside a template loop you access post.author.username or post.category.name for each one. Django hits the database once per post to fetch the related object. That's 21 queries instead of 2.

Fix it with select_related() for ForeignKey and OneToOne relationships:

posts = Post.objects.select_related('author', 'category').all()

2. Forgetting prefetch_related for ManyToMany

select_related() doesn't work for ManyToMany fields — you need prefetch_related(). Accessing post.tags.all() in a loop without it generates one query per post.

posts = Post.objects.prefetch_related('tags').all()

3. Fetching Columns You Don't Need

If you only need post titles and slugs for a listing page, don't fetch the entire row including the full content field. Use .only() to limit what Django retrieves:

posts = Post.objects.only('title', 'slug', 'published_at', 'excerpt')

4. Counting with len() Instead of count()

len(queryset) evaluates the queryset and loads all objects into memory just to count them. queryset.count() runs a SELECT COUNT(*) which is dramatically faster on large tables.

5. Missing Database Indexes

If you're filtering or ordering by a field frequently, it needs an index. published_at on a blog post model should have db_index=True. Without it, every query that orders by date scans the full table.

MI

Written by

Mubashar Iqbal

Web developer, SEO expert, and independent maker. I build products, write about what I've learned, and create free tools for developers and marketers.