← Back to Django, page 4

django-0070 · Medium mid

How do you use Exists() in Django to filter or annotate rows based on related data, and why is it better than count() or a join?

Exists(queryset) produces a SQL EXISTS subquery that stops at the first matching row. It can be used inside filter() to select rows with related matches, or in annotate() to add a boolean field. It avoids duplicates from joins, avoids counting every row, and negates cleanly with ~Exists(...). For a single object, queryset.exists() is the cheapest check.

Full answer

Question: which students have at least one mark of 80 or above, and which have none?

python
high = Mark.objects.filter(student=OuterRef("pk"), score__gte=80)
Student.objects.filter(Exists(high))           # Django 3.0+: Exists works directly in filter
Student.objects.filter(~Exists(high))          # students with none
Student.objects.annotate(has_high=Exists(high))

Why Exists:

  • A join filter(marks__score__gte=80) returns one row per matching mark, so students appear several times unless you add distinct().
  • annotate(Count(...)).filter(count__gt=0) counts all matches before checking, doing needless work and forcing a GROUP BY.
  • EXISTS can stop scanning after the first hit, especially with an index on the foreign key.

Related tools:

  • qs.exists() on a queryset returns a Python bool with SELECT 1 ... LIMIT 1. Prefer it over if qs: (loads all rows) and over qs.count() > 0 (counts all).
  • ~Exists(...) makes anti-joins ("students without marks") more reliable than exclude(marks__isnull=False) in complicated cases and avoids the NOT IN with NULL trap.
  • Combine with Q: filter(Exists(high) | Q(name="Asha")) works because Exists is a boolean expression that can be combined with | and &, or annotate first and filter on the annotation.
  • Use Exists in Case/When to build derived labels.

The same OuterRef rules apply: the inner query is correlated to the outer row. Add .order_by() if the inner queryset has default ordering; Django strips ordering inside Exists, so it is harmless.

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 Exists, OuterRef, Q

high = Mark.objects.filter(student=OuterRef("pk"), score__gte=80)
print("join duplicates:", Student.objects.filter(marks__score__gte=60).count(), "rows for", Student.objects.count(), "students")
print("exists:", [s.name for s in Student.objects.filter(Exists(high))])
print("not exists:", [s.name for s in Student.objects.filter(~Exists(high)).order_by("name")])

flagged = Student.objects.annotate(has_high=Exists(high)).order_by("name")
print([(s.name, s.has_high) for s in flagged])

mixed = Student.objects.filter(Exists(high) | Q(name="Asha")).order_by("name")
print([s.name for s in mixed])

print(Mark.objects.filter(score__gt=95).exists(), Mark.objects.filter(score__gt=50).exists())
print("LIMIT 1" in str(Mark.objects.filter(score__gt=50).query), "EXISTS" in str(Student.objects.filter(Exists(high)).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): join duplicates: 7 rows for 4 students exists: ['Kiran', 'Meera'] not exists: ['Asha', 'Ravi'] [('Asha', False), ('Kiran', True), ('Meera', True), ('Ravi', False)] ['Asha', 'Kiran', 'Meera'] False True False True

Key points

  • Exists stops at the first match
  • Works in filter() and annotate(); negate with ~
  • Avoids duplicate rows from joins and the cost of counting
  • Use qs.exists() instead of count() > 0 or truthiness
  • Anti-joins are clearer than exclude() across relations

Common mistakes

  • Using count() > 0 or if queryset: just to check existence
  • Joining a multi-valued relation and forgetting duplicates
  • Using exclude() across multi-valued relations and getting surprising results
  • Thinking Exists needs a values() call or ordering

Follow-ups

  • How does exclude() on a multi-valued relation behave?
  • Why is NOT IN with NULLs dangerous?
  • How do you combine Exists with OR conditions?

Tips

  • Contrast with join and count
  • Mention ~Exists for anti-joins
  • Mention qs.exists()