Full answer
Slow ORM code usually has one of four causes: too many queries (N+1), too much data per query, too many rows held in memory, or a query the database cannot answer efficiently. Fix the measured problem, not a guessed one.
Load fewer columns:
only("id", "name")loads just those fields; accessing another field triggers a query per object, so use it only when you know what the code touches.defer("biography")skips a large column such as a longTextField.values("name", "marks")returns dicts andvalues_list("name", flat=True)returns plain values. No model instances are built, which is much cheaper for reports and exports. You lose model methods.
Handle many rows:
- A normal QuerySet caches every row it loads. For 2 million attendance rows,
for a in qs.iterator(chunk_size=2000)streams results and keeps memory flat. Since Django 4.1,prefetch_relatedworks withiterator()when you passchunk_size. - Batch writes with
bulk_create/bulk_update, and useupdate()/delete()on a QuerySet instead of looping.
Let the database work:
exists()instead ofif qs:when you need a yes/no answer.count()instead oflen(qs).aggregate()/annotate()instead of summing in Python.Subquery,OuterRefandExistsfor "latest mark per student" style questions in one query.
Check the plan:
print(qs.query)shows SQL;qs.explain()(withanalyze=Trueon PostgreSQL) shows whether an index is used.- Add indexes that match real filters and orderings.
Watch out for: order_by("?") (random ordering scans the whole table), OFFSET pagination deep into big tables (prefer keyset pagination), and distinct() on wide rows.
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
import tracemalloc
from django.db import models, connection
from django.db.models import Exists, OuterRef, Subquery
class Student(models.Model):
name = models.CharField(max_length=40)
biography = models.TextField()
class Meta:
app_label = "school"
class Mark(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
score = models.IntegerField()
exam_no = models.IntegerField()
class Meta:
app_label = "school"
indexes = [models.Index(fields=["student", "-exam_no"], name="mark_student_exam_idx")]
with connection.schema_editor() as editor:
editor.create_model(Student)
editor.create_model(Mark)
Student.objects.bulk_create([Student(name=f"S{i:05d}", biography="x" * 2000) for i in range(5000)])
Mark.objects.bulk_create([Mark(student_id=i % 5000 + 1, score=(i * 7) % 101, exam_no=i // 5000)
for i in range(15000)])
def peak_kb(fn):
tracemalloc.start()
fn()
peak = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
return peak // 1024
full = peak_kb(lambda: [s.name for s in Student.objects.all()])
slim = peak_kb(lambda: list(Student.objects.values_list("name", flat=True)))
streamed = peak_kb(lambda: [s.name for s in Student.objects.only("name").iterator(chunk_size=500)])
print("values_list uses less memory than full rows:", slim < full)
print("only()+iterator() uses less memory than full rows:", streamed < full)
latest = Mark.objects.filter(student=OuterRef("pk")).order_by("-exam_no")
qs = (Student.objects
.annotate(latest_score=Subquery(latest.values("score")[:1]))
.filter(Exists(Mark.objects.filter(student=OuterRef("pk"), score=100)))
.order_by("name")
.values("name", "latest_score")[:3])
print(list(qs))
print("index used:", "mark_student_exam_idx" in Mark.objects.filter(student_id=1).order_by("-exam_no").explain())
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Memory numbers vary by machine, so the script prints comparisons instead of raw kilobytes. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): values_list uses less memory than full rows: True only()+iterator() uses less memory than full rows: True [{'name': 'S00021', 'latest_score': 53}, {'name': 'S00071', 'latest_score': 100}, {'name': 'S00072', 'latest_score': 6}] index used: True
Key points
- only/defer limit columns but keep instances
- values/values_list skip model creation
- iterator(chunk_size=...) streams without caching
- Push counting and summing into SQL
- Use explain() to confirm index use
Common mistakes
- Using only() and then touching deferred fields in a loop (one query per object)
- Loading full model instances for a CSV export of two columns
- Iterating millions of rows without iterator() and running out of memory
- Adding indexes without checking the plan with explain()
Follow-ups
- How would you get each student's latest mark in one query?
- Why is OFFSET pagination slow on large tables, and what is keyset pagination?
- When does iterator() not help on your database?
Tips
- Start with 'measure first' and name the tools
- Group fixes into columns, rows, and work pushed to SQL
- Mention Subquery/Exists for per-row lookups