2016-06-28 107 views
5

我有一个名为'StoreItem'的模型和一个名为'QuoteItem'的模型。 QuoteItem指向一个StoreItem。django注释 - 条件计数

我想注释一个有多少报价商品指向商店商品的计数器,但有条件适用于报价商品。

我想是这样的:

items = items.annotate(
      quote_count=Count(
       Case(
        When(quoteitem__lookup_date__in=this_week, then=1), 
        output_field=IntegerField() 
       ) 
      ) 
     ) 

'项目' 是StoreItems的查询集。 'this_week'是代表本周的日期列表(这是我尝试应用的过滤器)。在我使日期事情工作后,我想添加更多的过滤器到这个有条件的计数,但让我们开始。

反正什么我越来越更像是一个布尔 - 如果符合条件存在,不管我有多少有报价的项目,计数器为1。否则,将为0

它看起来像Count(Case())只检查是否有任何项目存在,如果是的话返回1,而我希望它遍历所有指向商店项目的报价项目并对它们进行计数,如果它们符合条件(单独)。

我该如何做到这一点?

回答

7

你需要在Sum语句而不是Count包裹的一切(我觉得有些奇怪,Count在所有工作):

from django.db.models import Case, IntegerField, Sum, When 

items = items.annotate(
     quote_count=Sum(
      Case(
       When(quoteitem__lookup_date__in=this_week, then=1), 
       output_field=IntegerField() 
      ) 
     ) 
    ) 

这基本上加起来所有的0 S和1 S为内部Case声明,导致匹配次数的计数。

0

我在做一个类似的任务。对我来说,的Case/When由于我加入了多少个表(这是计算的方式)而不工作。弄成这个样子:

from django.db.models import Case, IntegerField, Count, When, F 

items = items.annotate(
     quote_count=Count(
      Case(
       When(quoteitem__lookup_date__in=this_week, then=F('quoteitem__id'), 
      ), 
      distinct=True, 
     ) 
    ) 

在我来说,我其实是有添加两个Countš在一起,就像:

items = items.annotate(
     quote_count=Count(
      Case(
       When(quoteitem__lookup_date__in=this_week, then=F('quoteitem__id'), 
      ), 
      distinct=True, 
     ) 
    ) + Count (
      Case(
       When(itemgroup__lookup_date__in=this_week, then=F('itemgroup__quoteitem__id'), 
      ), 
      distinct=True, 
     ) 

假设items可以通过itemgroup或直接关系到quoteitems