Home > Mobile >  count each occurrences when date falls within a range
count each occurrences when date falls within a range

Time:10-11

I am trying to count each time the value of month in created_on falls within different months, using this django orm below:

    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")
)

I'm getting the error

When() supports a Q object, a boolean expression, or lookups as a condition.

When I apply Q notations to one of the cases, such as:

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

cannot unpack non-iterable bool object

Any suggestions?

CodePudding user response:

You could try something like this:

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")
)
  • Related