[Answered ]-Django: Combine two count annotations from two filter queries

1👍

I ended up solving with SubQuerys, as described in the first answer here.

qs1 = User.objects.filter(c1).annotate(count=Count('id')).filter(pk=OuterRef('pk'))
qs2 = User.objects.filter(c2).annotate(count=Count('id')).filter(pk=OuterRef('pk'))
users = User.objects.annotate(
    count1=Subquery(qs1.values('count'), output_field=IntegerField()),
    count2=Subquery(qs2.values('count'), output_field=IntegerField())
)

I still don’t fully understand the solution since this is the first time I’ve seen a SubQuery, but it seems to work. If anyone want to provide a more detailed answer I would be happy to accept it.

Leave a comment