3

I have a table transaction table and I tried this but it give transactions which present in database.

class transactions(models.Model):    
amount=models.FloatField()
ts = models.DateTimeField(null=True)

revenueByMonth = transactions.objects.annotate(month=TruncMonth('ts')).values('month').annotate(c=Sum('amount')).values('month', 'c')

It will give:

    <[
    {'c': 353.13, 'month': datetime.datetime(2016, 5, 1, 0, 0, tzinfo=<UTC>)}, 
    {'c': 706.26, 'month': datetime.datetime(2016, 8, 1, 0, 0, tzinfo=<UTC>)},
    {'c': 353.13, 'month': datetime.datetime(2016, 9, 1, 0, 0, tzinfo=<UTC>)},
    {'c': 706.26, 'month': datetime.datetime(2016, 10, 1, 0, 0, tzinfo=<UTC>)}, 
    {'c': 353.13, 'month': datetime.datetime(2016, 11, 1, 0, 0, tzinfo=<UTC>)}, 
    {'c': 756.26, 'month': datetime.datetime(2016, 12, 1, 0, 0, tzinfo=<UTC>)}
]>

I want sum of amount of each month and if a month have no transaction then it should be return zero.So please help me.

Rahul Gupta
  • 504
  • 4
  • 17

1 Answers1

0

I wont call this a duplicate but Django: Query Group By Month seems to atleast create a base for what you need. That is grouping by month.

Now for I want sum of amount of each month and if a month have no transaction then it should be return zero you can look into Coalesce. Combine this two and you should have your solution.

Community
  • 1
  • 1
Rajesh Yogeshwar
  • 2,111
  • 2
  • 18
  • 37