[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.

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

Leave a comment