【问题标题】:Annotate a queryset by a values queryset通过值查询集注释查询集
【发布时间】:2018-02-02 00:17:24
【问题描述】:

我想将对象计数注释到查询集,我知道该怎么做,但我希望计数的对象有自己的过滤器。

这很好用;

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

所以我现在有了一个很好的查询集,其中所有 first_model 计数按 second_model id 分组。惊人的。

我现在想做的是;

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

然后可以说secound_model_qs.first().first_model_count

这可能吗?

【问题讨论】:

    标签: python django django-models django-rest-framework


    【解决方案1】:

    我认为您可以使用 Subquery 更具体地通过 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)
    ) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      • 2017-07-09
      相关资源
      最近更新 更多