[Fixed]-Django group by dates and SUM values

13๐Ÿ‘

โœ…

Hmm you are using Count, you should use Sum, and values() will determine what goes into GROUP BY so you should use values('datetime') only. Your queryset should be something like this:

from django.db.models import Sum

values = self.model.objects.filter(
    datetime__range=(self.dates[0], self.dates[1])
).values('datetime').annotate(data_sum=Sum('data'))

although Iโ€™m not so sure about the order of the filter(), so it could be this:

values = self.model.objects.values('datetime').annotate(data_sum=Sum('data')).filter(
    datetime__range=(self.dates[0], self.dates[1])
)

I guess you would wanna try both then. If you want to see the raw query of those queryset, use Queryset.query:

print self.model.objects.filter(
    datetime__range=(self.dates[0], self.dates[1])
).values('datetime').annotate(data_sum=Sum('data')).query.__str__()

So you can make sure you get the right query.

Hope it helps.

๐Ÿ‘คHieu Nguyen

7๐Ÿ‘

order_by() will get you GROUP BY:

values = self.model.objects.filter(datetime__range=(
    self.dates[0], self.dates[1])) \
    .values('datetime') \
    .annotate(data_sum=Sum('datas') \
    .order_by())
๐Ÿ‘คdan-klasson

Leave a comment