← Back to Django, page 4

django-0071 · Medium mid

How do Case and When expressions work in the Django ORM, and where are they useful?

Case(When(condition, then=value), ..., default=value) builds a SQL CASE expression. It can derive labels in annotate(), choose custom sort orders in order_by(), count conditionally inside aggregates, and update different rows with different values in one UPDATE statement. Always provide default and output_field when the result type is not obvious.

Full answer

A CASE expression moves if/else logic into the database, so it applies to millions of rows in one query.

python
grade = Case(
    When(score__gte=80, then=Value("A")),
    When(score__gte=60, then=Value("B")),
    default=Value("C"),
    output_field=CharField(),
)
Mark.objects.annotate(grade=grade)

Uses:

  1. Derived labels: grade bands, status text, price tiers (annotate).
  2. Custom ordering: order_by(Case(When(status="urgent", then=0), When(status="normal", then=1), default=2)), for example pinning urgent items first.
  3. Conditional aggregation: Sum(Case(When(paid=True, then="amount"), default=0)) (also expressible with filter=).
  4. Bulk conditional update: one statement instead of a loop, Mark.objects.update(score=Case(When(score__lt=40, then=40), default=F("score"))).
  5. Conditional values in filters: annotate first, then filter(grade="A").

Details:

  • When accepts lookups (score__gte=80), a Q object, or a boolean expression such as Exists(...).
  • then takes a value, an F() reference or any expression; use Value(...) for literals when mixing types.
  • Conditions are evaluated in order and the first match wins, so order from the most specific to the least.
  • Without default, unmatched rows become NULL.
  • When mixing types (integers and strings) specify output_field.

Prefer CASE over a Python loop when you only transform values; prefer a lookup table or a model method when the rule needs to change often or is shown in many places.

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 Case, CharField, Count, F, IntegerField, Value, When

grade = Case(
    When(score__gte=80, then=Value("A")),
    When(score__gte=60, then=Value("B")),
    default=Value("C"),
    output_field=CharField(),
)
marks = Mark.objects.annotate(grade=grade).order_by("student__name", "subject")
print([(m.student.name, m.subject, m.score, m.grade) for m in marks.select_related("student")][:4])
print(list(Mark.objects.annotate(grade=grade).values("grade").annotate(n=Count("id")).order_by("grade")))

priority = Case(When(subject="Science", then=0), default=1, output_field=IntegerField())
print([(m.subject, m.score) for m in Mark.objects.order_by(priority, "-score")[:3]])

changed = Mark.objects.update(score=Case(When(score__lt=60, then=60), default=F("score")))
print(changed, "rows updated; lowest score now", min(Mark.objects.values_list("score", flat=True)))

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', 'Maths', 60, 'B'), ('Asha', 'Science', 55, 'C'), ('Kiran', 'Maths', 80, 'A'), ('Kiran', 'Science', 71, 'B')] [{'grade': 'A', 'n': 2}, {'grade': 'B', 'n': 5}, {'grade': 'C', 'n': 1}] [('Science', 79), ('Science', 71), ('Science', 63)] 8 rows updated; lowest score now 60

Key points

  • Case/When is SQL CASE: evaluated in order, first match wins
  • Use in annotate, order_by, aggregates and update
  • Provide default and output_field
  • A single UPDATE can apply different values by condition
  • Prefer it over Python loops for bulk transforms

Common mistakes

  • Forgetting default and getting NULL for unmatched rows
  • Ordering conditions from least to most specific
  • Mixing value types without output_field
  • Looping in Python to update rows that one CASE update could handle

Follow-ups

  • How would you use Case/When to pin certain rows first in a list?
  • How does conditional aggregation with filter= compare?
  • How do you update rows with different values in a single query?

Tips

  • Show a grade-band example
  • Mention first match wins
  • Mention bulk update