簡體   English   中英

django annotate - 條件計數

[英]django annotate - conditional count

我有一個名為'StoreItem'的模型和一個名為'QuoteItem'的模型。 QuoteItem指向StoreItem。

我正在嘗試注釋一個計數器,該計數器指出商店項目上有多少引用項目,但是條件適用於報價項目。

我試過這樣的事情:

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

'items'是StoreItems的查詢集。 'this_week'是代表本周的日期列表(這是我嘗試應用的過濾器)。 在我使日期工作之后,我想為這個條件計數添加更多過濾器,但讓我們開始吧。

無論如何我得到的更像是一個布爾值 - 如果符合條件的引用項存在,無論我有多少,計數器將是1.否則,將為0。

它看起來像Count(Case())只檢查是否存在任何項目,如果存在則返回1,而我希望它迭代指向商店項目的所有引用項目並計算它們,如果它們匹配條件(單獨) 。

我該如何實現?

你需要將所有內容都包含在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()
            )
        )
    )

這基本上將內部Case語句的所有01加起來,從而得到匹配數的計數。

我正在做類似的任務。 對我來說, SumCase/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可以通過items itemgroup或直接與quoteitems相關quoteitems

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM