0Pricing
Django Academy · Lesson

Conditional Aggregation with Case/When

Branch logic inside a single query.

Branching Inside a Query

Sometimes you need different results for different rows. Case lets the database choose a value per row, like an if statement in SQL.

The Case and When Pair

A Case holds one or more When branches; each When pairs a condition with the value to use when that condition is true.

from django.db.models import Case, When, Value

All lessons in this course

  1. aggregate vs annotate
  2. F Expressions for Atomic Updates
  3. Q Objects for Complex Filters
  4. Conditional Aggregation with Case/When
← Back to Django Academy