Django 按月/按季度对 DateField() 数据进行分组
我有一个 django 模型,其中包含一个 DateField() 属性:
class Table():
date = models.DateField()
value = models.FloatField()
我正在编写一个视图,按周、月、季度和年份对这些数据进行分组。 我已经硬编码了一个计算,通过将当月的所有值相加并除以有多少条目,可以简单地获得我的每月值 - 但我觉得必须有一种更优雅的方法来做到这一点。
我的目标是这样的:
get_monthly(Table.objects.all())
>>> [123, 412, 123, 534, 234, 423, 312, 412, 123, 534, 234, 423]
get_quarterly(Table.objects.all())
>>> [123, 412, 123, 534]
列表中的值是每个月的平均值。
谁能帮助我吗?
I've got a django model which contains, among other things, a DateField() attribute:
class Table():
date = models.DateField()
value = models.FloatField()
I'm writing a view that groups this data by week, month Quarter and year.
I've hardcoded a calculation that gets my monthly value simply enough - by adding up all the values in that month and deviding by how many entries there were - but I feel like there must be a more elegant way of doing this.
What I'm aiming for is something like this:
get_monthly(Table.objects.all())
>>> [123, 412, 123, 534, 234, 423, 312, 412, 123, 534, 234, 423]
get_quarterly(Table.objects.all())
>>> [123, 412, 123, 534]
Where the values in the list are averages of each month.
Can anyone help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用模型的查询功能来完成此操作。
以下是每月查询的示例:
您可能希望将
strftime('%m',date)
更改为month(date)
或任何其他计算,具体取决于您的情况数据库日期时间功能。You can do this using the model's query capabilities.
Here's an example for the monthly query:
Where you may want to change
strftime('%m',date)
withmonth(date)
or any other calculation, depending on your database datetime functionality.