Code works fine without subquery, why to use it?

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

And,

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

Both, works fine then why use a Subquery, what are its advantages?

Subqueries can make it easier to write complex queries, as you can break down the query into smaller, more manageable pieces. How to use subquery

In Your case that query wasn't so complicated.

Back to Top