Back to Articles
2024-02-28

Advanced Patterns: Subquery and Exists

For complex data requirements, standard lookups aren't enough. `Subquery` allows you to embed a query within another query, while `Exists` is optimized for checking relationships efficiently.

Scenario 1: Subquery (Latest Related Item)

Annotate the most recent comment text onto each post.

python
from django.db.models import OuterRef, Subquery

newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')
posts = Post.objects.annotate(
    latest_comment=Subquery(newest.values('text')[:1])
)

Scenario 2: Exists (Boolean Check)

Check if a user has any premium subscriptions efficiently.

python
from django.db.models import Exists, OuterRef

has_premium = Subscription.objects.filter(user=OuterRef('pk'), type='Premium')
users = User.objects.annotate(is_premium=Exists(has_premium))