gpt4 book ai didi

python - 如何按月从数据库组中检索数据并在 Django 中的某个月份没有值时返回零?

转载 作者:行者123 更新时间:2023-12-05 07:45:52 27 4
gpt4 key购买 nike

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

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>)}
]>

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

最佳答案

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

现在我想要每个月的金额总和,如果一个月没有交易那么它应该返回零你可以查看Coalesce .结合这两者,您应该有自己的解决方案。

关于python - 如何按月从数据库组中检索数据并在 Django 中的某个月份没有值时返回零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41159166/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com