【问题标题】:How to retrive data from db group by month and return zero if no value for certain month in django?如果django中某个月份没有值,如何按月从db组中检索数据并返回零?
【发布时间】:2017-04-30 18:15:54
【问题描述】:

我有一个表事务表,我尝试了这个,但它给出了数据库中存在的事务。

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

它会给出:

    <[
    {'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>)}
]>

我想要每个月的金额总和,如果一个月没有交易,那么它应该返回零。所以请帮助我。

【问题讨论】:

    标签: python django


    【解决方案1】:

    我不会将其称为重复,但 Django: Query Group By Month 似乎至少为您的需要创建了一个基础。即按月分组。

    现在对于I want sum of amount of each month and if a month have no transaction then it should be return zero,您可以查看Coalesce。结合这两者,你应该有你的解决方案。

    【讨论】:

    • 感谢您的回答。我尝试了 Coalesce,但没有给出预期的答案。如果您有解决方案,请帮助我
    • 首先显示您尝试的代码段,包括使用 Coalesce
    • revenueByMonth = transactions.objects.annotate(month=TruncMonth('ts')).values('month').annotate(c=Coalesce(Sum('amount'),V(0) )).values('月', 'c')
    猜你喜欢
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多