Reputation: 185
I am trying count all my id
and group by
month in Django.
My id field is a Datetime
has the format "2020-07-26 22:08:55.747424", harder than I thought. Been looking at other examples as well without any luck.
Any suggestions?
My current Queryset while experimenting
myquery = alldata.objects.all().filter(id__year="2020").annotate(date=TruncMonth('id'),).values(('month').annotate(total_entries=Count('id')))
Error message
AttributeError at /page/
'str' object has no attribute 'annotate'
Upvotes: 1
Views: 519
Reputation: 476503
You made a bracket mistake, it should be:
myquery = alldata.objects.all().filter(id__year="2020").annotate(date=TruncMonth('id'),).values(('month')).annotate(total_entries=Count('id'))
So with an extra closing parenthesis )
after 'month')
. You furthermore used month
in your values, but the annotation is named date=…
.
You can however simplify this to:
myquery = alldata.objects.filter(id__year='2020').values(
month=TruncMonth('id')
).annotate(
total_entries=Count('id')
).order_by('month')
The .order_by(…)
is necessary if you later subscript, like …[0]
, then it will not perform a GROUP BY
without using a .order_by(…)
.
Upvotes: 2