2016-06-28 108 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