I have code that looks like the following:
filtered_queryset = Object.objects.filter(...misc filters)
match time:
case "year":
qs = filtered_queryset.annotate(year=TruncYear("created_at")).values("year")
case "month":
qs = filtered_queryset.annotate(month=TruncMonth("created_at")).values("month")
case "week":
qs = filtered_queryset.annotate(week=TruncWeek("created_at")).values("week")
case _:
qs = filtered_queryset
final_count = qs.annotate(count=Count("id"))
In each case, I am expecting data that looks like the following
# Each case
{
[{
"TIME": ...
"count": ...
},
...
]
}
# Default
{
[{
"count": ...
}]
}
I was under the impression that Count()
was a terminal expression in django and that the queryset would be evaluated. However, the default case returns a queryset instead of evaluating. What am I missing here that causes it to not evaluate the queryset?
I know that I can just call filtered_queryset.count()
instead of trying to do this via annotate, but it causes extra code to check for the default case and adds code smell.