A
A
Anton2019-12-24 16:23:02
Django
Anton, 2019-12-24 16:23:02

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'))))

Tell me, what's wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question