Django每月/每季度分组DateField()数据 [英] Django Monthly/quartarly grouping of DateField() data
问题描述
我有一个django模型,其中包含一个 DateField()属性:
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.
我的目标是这样的:
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?
推荐答案
该模型的查询功能。
以下是每月查询的示例:
You can do this using the model's query capabilities. Here's an example for the monthly query:
from django.db.models import Avg
Table.objects.extra(select={'month':"strftime('%m',date)"}).values('month').annotate(Avg('value'))
您可能希望将 strftime('%m',date)
code>月(日期)或任何其他计算,具体取决于您的数据库日期时间功能。
Where you may want to change strftime('%m',date)
with month(date)
or any other calculation, depending on your database datetime functionality.
这篇关于Django每月/每季度分组DateField()数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!