← Back to Django, page 4

django-0069 · Medium mid

How do Subquery and OuterRef work in the Django ORM, and when do you choose them over joins or Python loops?

Subquery(queryset) embeds a queryset as a scalar subquery inside another query, and OuterRef("field") refers to a column of the outer query. Use it to annotate each row with a value taken from a related table that needs ordering or LIMIT, such as each student's best mark, without per-row queries or duplicate rows from joins. The inner queryset must return one column and at most one row.

Full answer

Problem: list every student with the score and subject of their highest mark. A join gives one row per mark; a Python loop gives N+1 queries. A correlated subquery gives exactly one value per student in one statement.

python
best = Mark.objects.filter(student=OuterRef("pk")).order_by("-score")
Student.objects.annotate(
    best_score=Subquery(best.values("score")[:1]),
    best_subject=Subquery(best.values("subject")[:1]),
)

Rules:

  • The inner queryset must select a single column (values("score")) and must be limited to one row ([:1]), otherwise the database raises an error ("more than one row returned").
  • OuterRef("pk") is resolved against the outer query when the subquery is executed. OuterRef(OuterRef("x")) reaches two levels up.
  • Subqueries can also appear in filter(): Student.objects.filter(id__in=Mark.objects.filter(score__gt=70).values("student")).
  • If the subquery may return no row, the annotation is NULL; add Coalesce(Subquery(...), 0) with output_field for a default.
  • Provide output_field when Django cannot infer the type of the result.

Choose by need: select_related and prefetch_related for fetching related objects, annotate(Count/Sum) for aggregates over a relation, Subquery for "latest or top row per group" and cases needing ordering and LIMIT, and Exists for yes or no questions.

Check the SQL with str(qs.query) and measure with explain(); correlated subqueries run per outer row, which is fine with an index on the foreign key (Mark.student, indexed by default).

python
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()

from django.db import models, connection
from django.test.utils import CaptureQueriesContext


class ClassRoom(models.Model):
    name = models.CharField(max_length=10)
    class Meta:
        app_label = "school"


class Student(models.Model):
    name = models.CharField(max_length=40)
    class_room = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name="students")
    class Meta:
        app_label = "school"


class Mark(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
    subject = models.CharField(max_length=20)
    score = models.IntegerField()
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    for m in (ClassRoom, Student, Mark):
        editor.create_model(m)

a, b = ClassRoom.objects.create(name="10A"), ClassRoom.objects.create(name="10B")
for i, (name, room) in enumerate([("Asha", a), ("Ravi", a), ("Kiran", b), ("Meera", b)]):
    s = Student.objects.create(name=name, class_room=room)
    Mark.objects.create(student=s, subject="Maths", score=60 + i * 10)
    Mark.objects.create(student=s, subject="Science", score=55 + i * 8)

from django.db.models import OuterRef, Subquery, IntegerField
from django.db.models.functions import Coalesce

best = Mark.objects.filter(student=OuterRef("pk")).order_by("-score")
qs = Student.objects.annotate(
    best_score=Subquery(best.values("score")[:1]),
    best_subject=Subquery(best.values("subject")[:1]),
).order_by("name")

with CaptureQueriesContext(connection) as ctx:
    rows = [(s.name, s.best_score, s.best_subject) for s in qs]
print(rows)
print("queries:", len(ctx))

weak = Student.objects.filter(id__in=Mark.objects.filter(score__lt=58).values("student"))
print([s.name for s in weak])

newcomer = Student.objects.create(name="Newcomer", class_room=ClassRoom.objects.first())
safe = Student.objects.filter(pk=newcomer.pk).annotate(
    best=Coalesce(Subquery(best.values("score")[:1]), 0, output_field=IntegerField())
).get()
print(safe.best)
print("(SELECT" in str(qs.query))

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. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): [('Asha', 60, 'Maths'), ('Kiran', 80, 'Maths'), ('Meera', 90, 'Maths'), ('Ravi', 70, 'Maths')] queries: 1 ['Asha'] 0 True

Key points

  • Subquery embeds a queryset; OuterRef points to the outer row
  • Inner query must return one column and one row
  • Gives per-row values without N+1 or duplicate join rows
  • NULL when the subquery is empty; use Coalesce
  • Index the foreign key used in the correlation

Common mistakes

  • Returning several columns or several rows from the inner queryset
  • Forgetting [:1] on an ordered inner queryset
  • Looping in Python and querying per object
  • Not providing output_field when Django cannot infer it

Follow-ups

  • How does Subquery differ from Exists?
  • How would you get the latest 3 marks per student?
  • When does a window function replace a subquery?

Tips

  • Explain correlation with OuterRef
  • State the one-column, one-row rule
  • Compare with joins and prefetch