惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
小众软件
小众软件
博客园 - 司徒正美
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Jina AI
Jina AI
Hugging Face - Blog
Hugging Face - Blog
博客园 - Franky
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
量子位
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
雷峰网
雷峰网
云风的 BLOG
云风的 BLOG
M
MIT News - Artificial intelligence
F
Fortinet All Blogs
T
Tailwind CSS Blog
Martin Fowler
Martin Fowler
I
InfoQ
The GitHub Blog
The GitHub Blog
有赞技术团队
有赞技术团队
The Cloudflare Blog
罗磊的独立博客

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
The N+1 Query Problem That's Silently Slowing Your Django...
Houssem Regg · 2026-04-25 · via DEV Community

100 orders. A loop. A template that accesses order.user.email. Result: 701 database queries. Here is how it happens — and how to fix it in one line.

The N+1 query problem is the most common performance issue in Django applications. It is also the most invisible one in development, because your local database has twenty records. It only becomes visible in production, where it has twenty thousand — and by then, it is an incident.

The ORM does not hide SQL from you. It writes SQL for you. Understanding what SQL it writes — and why — is what separates ORM users from ORM professionals.

How N+1 Happens

Here is a view that looks perfectly innocent:

# views.py — looks clean, causes disaster at scale
def order_list(request):
    orders = Order.objects.all()  # Query 1: SELECT * FROM orders
    return render(request, 'orders/list.html', {'orders': orders})

Enter fullscreen mode Exit fullscreen mode

Then in the template:

{# orders/list.html #}
{% for order in orders %}
    {{ order.user.email }}      {# Query 2,3,...N: SELECT user WHERE id=? #}
    {% for item in order.items.all %}
        {{ item.product.name }} {# Query N+1, N+2... for each item #}
    {% endfor %}
{% endfor %}

Enter fullscreen mode Exit fullscreen mode

For 100 orders with 5 items each, this template fires:

  • 1 query to fetch all orders
  • 100 queries to fetch each order's user
  • 100 queries to fetch each order's items
  • 500 queries to fetch each item's product — total: 701 queries

Every page load. Every visitor. The database CPU climbs. Response times degrade. And because it works fine locally with your 10 test records, no one notices until production slows to a crawl.

The Fix: select_related and prefetch_related

Django provides two tools for solving N+1, and using the right one matters.

select_related — for ForeignKey and OneToOne

Use select_related when traversing ForeignKey or OneToOneField relationships. It generates a SQL JOIN and fetches everything in one query:

# BAD: 1 + N queries
orders = Order.objects.all()

# GOOD: 1 query with a JOIN
orders = Order.objects.select_related('user', 'shipping_address')

# Multi-level: traverse FK chains
orders = Order.objects.select_related('user__profile')

Enter fullscreen mode Exit fullscreen mode

prefetch_related — for reverse FK and ManyToMany

Use prefetch_related for reverse ForeignKey relationships and ManyToManyFields — relationships where the related object is a collection. It executes a separate query per relationship and joins the results in Python:

# BAD: 1 query for orders + N queries for items + N*M for products
orders = Order.objects.all()

# GOOD: 3 queries regardless of order count
# Query 1: SELECT * FROM orders
# Query 2: SELECT * FROM order_items WHERE order_id IN (...)
# Query 3: SELECT * FROM products WHERE id IN (...)
orders = Order.objects.prefetch_related('items__product')

# Combine both for the full solution:
orders = (
    Order.objects
    .select_related('user', 'shipping_address')
    .prefetch_related('items__product')
    .filter(status='paid')
    .order_by('-created_at')
)

Enter fullscreen mode Exit fullscreen mode

⚠ A common mistake that defeats prefetch_related
Filtering a prefetched relation inside a loop re-fires a query per object and completely defeats the prefetch. This is the trap:

for order in orders:  # prefetched
    active_items = order.items.filter(is_active=True)  # NEW query each time!

Enter fullscreen mode Exit fullscreen mode

Fix: use a Prefetch object with a custom queryset to apply the filter at prefetch time.

How to Detect N+1: django-debug-toolbar

Install django-debug-toolbar in your development environment and make the SQL panel part of your workflow. It shows every query executed during a request, the time each took, and whether any are duplicates.

# requirements/local.txt
django-debug-toolbar==4.3.0

# config/settings/local.py
INSTALLED_APPS += ['debug_toolbar']
MIDDLEWARE.insert(1, 'debug_toolbar.middleware.DebugToolbarMiddleware')
INTERNAL_IPS = ['127.0.0.1']

Enter fullscreen mode Exit fullscreen mode

A healthy page has under 10 queries. A page with 50+ has an N+1 problem. Treat the SQL panel as a mandatory check before every feature is considered done.

Lock it in with Query Count Tests

The best way to prevent N+1 regressions is to assert query counts in your test suite:

from django.test import TestCase

class OrderListViewTest(TestCase):
    def test_query_count_is_bounded(self):
        user = UserFactory()
        OrderFactory.create_batch(20, user=user)

        self.client.force_login(user)
        with self.assertNumQueries(3):  # orders + users + items
            response = self.client.get('/orders/')

        self.assertEqual(response.status_code, 200)

Enter fullscreen mode Exit fullscreen mode

This test will fail the moment someone adds a line to the view that introduces an N+1. That failure, caught in CI before it reaches production, is exactly what the test is for.

The N+1 problem is not unique to Django — it appears in every ORM-based framework. But Django's ORM makes it particularly invisible because querysets are lazy and the query only fires at iteration time, often deep in a template. select_related and prefetch_related are the tools designed to solve it. Learn to reach for them automatically whenever you access a related object.