简体   繁体   English

用值queryset注释queryset

[英]Annotate a queryset by a values queryset

I want to annotate a count of objects to a queryset, which I know how to do, but I want the objects counted to have their own filtering. 我想将一定数量的对象注释到一个查询集中,我知道该怎么做,但是我希望对对象计数要有自己的过滤条件。

This works well; 这很好用;

first_model_qs = FirstModel.objects.filter(do a bunch of filtering)
grouped_values_qs = first_model_qs.values('second_model').annotate(Count('pk'))

So I now have a nice queryset with all the first_model counts grouped by second_model ids. 因此,我现在有了一个不错的查询集,其中所有的first_model计数second_model ID分组。 Awesome. 太棒了

What I'd like to do now is something like; 我现在想做的是

secound_model_qs = SecondModel.objects.annotate(first_model_count = grouped_values_qs)

And then be able to say secound_model_qs.first().first_model_count 然后可以说出secound_model_qs.first().first_model_count

Is this possible? 这可能吗?

I think you can do it with a Subquery and more specifically by Using aggregates within a Subquery expression 我认为您可以使用子查询来实现 ,更具体地说,可以通过在子查询表达式内使用聚合来实现

from django.db.models import OuterRef, Subquery, Count

first_model_query = (FirstModel.objects
    # Do the filtering
    .filter(second_model=OuterRef('pk'))
    # add grouping
    .values('second_model')
    # do the aggregation
    .annotate(cnt=Count('pk'))
    # now return only a single column
    .values('cnt')
)

secound_model_qs = SecondModel.objects.annotate(
    first_model_count=Subquery(first_model_query)
) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM