0

I have model whose instance creating every hour:

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

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

I want to get average values for days of last month e.g. 30 instances containing average value for every day. How to realize it? Now I've wrote this method:

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)

What should I do to implement funcionality?

Vassily
  • 5,263
  • 4
  • 33
  • 63

2 Answers2

2

You're doing everything right except returning value. Aggregated query shouldn't be an Entry instance

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}

This will return a dict like

{'temperature': 202.48803054780439,
 'no2': 4881.734909678366,
 'co': None,
 'humidity': 200}
Andrey Nelubin
  • 3,084
  • 1
  • 20
  • 25
0

I am suggesting that you can execute some script.py regularly via a job scheduler. the script.py may be like this to deal with your django project off the django shell;

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 ...
Leonard2
  • 894
  • 8
  • 21