【问题标题】:count each occurrences when date falls within a range当日期在一个范围内时计算每次出现
【发布时间】:2021-11-29 19:31:36
【问题描述】:

我正在尝试计算 created_on 中的月份值每次落在不同月份时,使用下面的这个 django orm:

    result_qs = Model.objects.all().annotate(
        spring=Count(Case(When(ExtractMonth("created_on") in [1, 2, 3, 4, 5], then=1))),
        summer=Count(Case(When(ExtractMonth("created_on") in [6, 7], then=1))),
        fall=Count(Case(When(ExtractMonth("created_on") in [8, 9, 10, 11, 12], then=1))),
        year=ExtractYear("created_on")
)

我收到了错误

When() 支持 Q 对象、布尔表达式或查找作为 条件。

当我将Q 符号应用于其中一种情况时,例如:

spring=Count(Case(When(Q(ExtractMonth("created_on") in [1, 2, 3, 4, 5], then=1)))),

无法解压不可迭代的 bool 对象

有什么建议吗?

【问题讨论】:

    标签: python django postgresql orm


    【解决方案1】:

    你可以试试这样的:

    result_qs = Model.objects.all().annotate(
            spring=Count(Case(When(created_on__month__in=[1, 2, 3, 4, 5], then=1))),
            summer=Count(Case(When(created_on__month__in=[6, 7], then=1))),
            fall=Count(Case(When(created_on__month__in=[8, 9, 10, 11, 12], then=1))),
            year=ExtractYear("created_on")
    )
    

    【讨论】:

    • 工作就像一个魅力。谢谢。我不知道__month__ 是可能的。
    • 很高兴我能帮上忙。还有其他日期:__day__year__week
    猜你喜欢
    • 2010-11-26
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多