当日期在一个范围内时计算每次出现的次数
count each occurrences when date falls within a range
我试图计算每次 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() supports a Q object, a boolean expression, or lookups as a
condition.
当我对其中一种情况应用 Q
符号时,例如:
spring=Count(Case(When(Q(ExtractMonth("created_on") in [1, 2, 3, 4, 5], then=1)))),
cannot unpack non-iterable bool object
有什么建议吗?
您可以尝试这样的操作:
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")
)
我试图计算每次 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() supports a Q object, a boolean expression, or lookups as a condition.
当我对其中一种情况应用 Q
符号时,例如:
spring=Count(Case(When(Q(ExtractMonth("created_on") in [1, 2, 3, 4, 5], then=1)))),
cannot unpack non-iterable bool object
有什么建议吗?
您可以尝试这样的操作:
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")
)