Django: Group by date then calculate Sum of amount for each date

Viewed 3131

I have a django model like. it stores total transactions happened over time periods.

class Transaction(models.Model):
    amount = models.FloatField()
    seller = models.ForeignKey(User, related_name='sells', on_delete=models.CASCADE)
    buyer = models.ForeignKey(User, related_name='purchased', on_delete=models.CASCADE)
    created_at_date = models.DateField(auto_now_add=True)

my question:

is that how can i find total amount of transactions for each day. for each day it should calculate Sum of all transactions in that day.

I need for example do this for last 7 days.

1 Answers

Found the solution, Query below will work:

Transaction.objects.filter().values('created_at__date').order_by('created_at__date').annotate(sum=Sum('amount'))

result will be:

<QuerySet [{'created_at__date': datetime.date(2019, 1, 3), 'sum': 10000000.0}, {'created_at__date': datetime.date(2019, 1, 4), 'sum': 4367566577.0}]>
Related