Answer the question
In order to leave comments, you need to log in
How to add a calculated field with an aggregation and a subquery in Django?
There are Blog (id, name) and Article (id, name, type) models.
I want to create an annotation with a count of the number of "a" type articles in each blog.
I try like this, but I get 1.
from django.db.models import Count, OuterRef, Subquery
articles_of_type_a = Article.objects.filter(blog=OuterRef('id'), type='a')
Blog.objects.annotate(type_a_count=Count(Subquery(articles_of_type_a.values('id'))))
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question