如何在django中聚合数据?

时间:2016-03-26 11:56:26

标签: python django django-aggregation

我的模型的实例每小时创建一次:

class Entry(models.Model):
    class Meta:
        ordering = ['time']

    time = models.DateTimeField()
    no2 = models.FloatField()
    co = models.FloatField()
    humidity = models.FloatField()
    temperature = models.FloatField()

我想获得上个月的平均值,例如30个实例,包含每天的平均值。怎么实现呢?现在我写了这个方法:

def average_for_period(self, start, end):
        entries_for_period = Entry.objects.filter(time__gte=start, time__lte=end)
        average_value = entries_for_period.aggregate(Avg('temperature'), Avg('no2'), Avg('co'), Avg('humidity'))
        return Entry(**average_value)

我应该怎样做才能实现功能?

2 个答案:

答案 0 :(得分:2)

除了返回价值之外,你做的一切正常。聚合查询不应该是Entry实例

oldObject.getHistories().clear();
for (History history : newObject.getHistories()) {
    history.setCompany(oldObject);
    oldObject.getHistories().add(history);
}

这会返回像

这样的字典
avg_values = ['temperature', 'no2', 'co', 'humidity']
average_value = entries_for_period.aggregate(*[Avg(x) for x in avg_values])
return {x:average_value['%s__avg' % x] for x in avg_values}

答案 1 :(得分:0)

我建议您可以通过作业调度程序定期执行一些script.py. script.py可能就像这样处理django shell上的django项目;

import sys, os

PATH_TO_DJANGO = 'path/to/django/project'
sys.path.append(PATH_TO_DJANGO)
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'

from app import Entry # can be imported after the above config...
import average_for_period # your custom function

# do what you want to ...