今日已更新 166 条资讯 | 累计 20138 条内容
关于我们

Optimizing Django ORM Queries: A Practical Guide to select_related and prefetch_related

Heitor Vasconcelos 2026年06月22日 08:02 2 次阅读 来源:Dev.to

1. Introduction Django's ORM is one of its greatest strengths. It abstracts away raw SQL, lets you express database operations in clean Python, and gets you productive fast. But that convenience comes with a hidden cost: if you're not deliberate about how you fetch related objects, you'll silently generate far more queries than you intend — and you won't notice until your app slows to a crawl in production. The most common culprit is the N+1 query problem : a pattern where fetching a list of N objects triggers an additional query for each one, resulting in N+1 total round-trips to the database. At ten rows it's invisible. At ten thousand rows, it's a disaster. Django provides two tools to fix this: select_related and prefetch_related . This article explains how each one works internally, when to use which, and how to combine them effectively — with before/after examples and real query counts throughout. 2. Understanding the N+1 Problem Consider a simple blog with posts and authors. You want to render a list of posts, showing each post's title and its author's name. Models: # models.py from django.db import models class Author ( models . Model ): name : str = models . CharField ( max_length = 100 ) class Post ( models . Model ): title : " str = models.CharField(max_length=200) " author : Author = models . ForeignKey ( Author , on_delete = models . CASCADE , related_name = " posts " , ) The naive approach: # views.py from django.db import connection from .models import Post def list_posts () -> None : posts = Post . objects . all () # Query 1: fetch all posts for post in posts : print ( f " { post . title } by { post . author . name } " ) # ^^^ Query 2, 3, 4, ... N+1: one per post For 100 posts, this produces 101 queries . Django lazily fetches post.author the first time you access it on each object. Each access hits the database separately. You can verify this with django.db.connection.queries (requires DEBUG = True ): from django.db import connection , reset_queries

本文内容来源于互联网,版权归原作者所有
查看原文