Full answer
Question: which students have at least one mark of 80 or above, and which have none?
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 adddistinct(). annotate(Count(...)).filter(count__gt=0)counts all matches before checking, doing needless work and forcing a GROUP BY.EXISTScan 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 withSELECT 1 ... LIMIT 1. Prefer it overif qs:(loads all rows) and overqs.count() > 0(counts all).~Exists(...)makes anti-joins ("students without marks") more reliable thanexclude(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
ExistsinCase/Whento 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.
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()