← Back to Django, page 4

django-0072 · Medium mid

How do you use window functions such as Rank, Lag and running totals with Django's Window expression, and how do they differ from aggregation?

A window function computes a value for each row using a set of related rows (the window) without collapsing rows like GROUP BY does. In Django you wrap functions such as Rank, DenseRank, RowNumber, Lag, Lead or Sum in Window(expression, partition_by=..., order_by=...). Since Django 4.2 you can filter directly on a window annotation, for example to get the top 2 per group.

Full answer

Aggregation collapses rows: one row per group. Window functions keep every row and add a computed column.

python
Mark.objects.annotate(
    rank=Window(Rank(), partition_by=F("subject"), order_by=F("score").desc())
)

Parts of Window:

  • expression: Rank(), DenseRank(), RowNumber(), Lag("score"), Lead("score"), FirstValue, NthValue, Ntile(4), or an aggregate like Sum("score").
  • partition_by: restarts the calculation per group (here per subject).
  • order_by: defines order inside each partition. For Sum, an ordered window gives a running total.
  • frame: RowRange(start=-2, end=0) for moving averages.

Typical uses: top N per group, ranking with ties (Rank leaves gaps, DenseRank does not, RowNumber is unique), previous-row differences (Lag), running totals, percentiles via Ntile and share of total (F("score") / Window(Sum("score"))).

Filtering: before Django 4.2 you had to wrap the query in a subquery. In 4.2 and later, .filter(rank__lte=2) works directly on the annotation and Django wraps the query for you.

Support: SQLite 3.25+, PostgreSQL, MySQL 8+, MariaDB 10.2+, Oracle. Window expressions cannot be mixed with aggregates in some ways, and very large partitions need indexes matching partition_by and order_by for speed.

Choose window functions over Python processing when ranking or comparing neighbouring rows, because the database does it in one pass.

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 F, Sum, Window
from django.db.models.functions import DenseRank, Lag, RowNumber, Rank

ranked = Mark.objects.annotate(
    rank=Window(Rank(), partition_by=F("subject"), order_by=F("score").desc()),
).order_by("subject", "rank")
print([(m.subject, m.student.name, m.score, m.rank) for m in ranked.select_related("student")][:4])

top2 = Mark.objects.annotate(
    rn=Window(RowNumber(), partition_by=F("subject"), order_by=F("score").desc())
).filter(rn__lte=2).order_by("subject", "rn")
print([(m.subject, m.score) for m in top2])

running = Mark.objects.filter(subject="Maths").annotate(
    prev=Window(Lag("score"), order_by=F("score").asc()),
    running=Window(Sum("score"), order_by=F("score").asc()),
).order_by("score")
print([(m.score, m.prev, m.running) for m in running])

share = Mark.objects.filter(subject="Science").annotate(pct=100 * F("score") / Window(Sum("score"))).order_by("score")
print([round(m.pct, 1) for m in share])

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. Needs SQLite 3.25 or newer (any modern Python build). Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): [('Maths', 'Meera', 90, 1), ('Maths', 'Kiran', 80, 2), ('Maths', 'Ravi', 70, 3), ('Maths', 'Asha', 60, 4)] [('Maths', 90), ('Maths', 80), ('Science', 79), ('Science', 71)] [(60, None, 60), (70, 60, 130), (80, 70, 210), (90, 80, 300)] [20, 23, 26, 29]

Key points

  • Windows keep all rows; aggregation collapses them
  • partition_by restarts per group; order_by orders inside it
  • Rank has gaps, DenseRank does not, RowNumber is unique
  • Lag/Lead read neighbouring rows; ordered Sum gives running totals
  • Django 4.2+ can filter on window annotations

Common mistakes

  • Expecting Window to reduce rows like aggregate()
  • Forgetting order_by inside Window for rank and running totals
  • Confusing Rank, DenseRank and RowNumber with ties
  • Filtering on window values in a way not supported before Django 4.2

Follow-ups

  • How do you get the latest row per group using a window function?
  • What is the difference between a frame and a partition?
  • How does this compare with a correlated subquery?

Tips

  • Define partition and order
  • Contrast Rank and DenseRank
  • Mention filtering on windows in 4.2