Django response set aggregation by time interval

Hi, I am writing a Django view that outputs data for graphical display on client side (High Charts). The data are climate data with a set parameter recorded once a day.

My request is this:

format = '%Y-%m-%d' 
sd = datetime.datetime.strptime(startdate, format)
ed = datetime.datetime.strptime(enddate, format)

data = Climate.objects.filter(recorded_on__range = (sd, ed)).order_by('recorded_on')

      

Now that the range is increased, the dataset is obviously getting bigger, and it doesn't show well on the graph (apart from a significant slowdown in pace).

Is there a way to group my data as averages over time periods - average for each month or average for each year?

I understand it can be done in SQL, as stated here: django aggregation for lower resolution using grouping by date range

But I would like to know if there is a convenient way in Django itself.

Or is it perhaps better to modify the db directly and use a script to populate the month and year fields from the timestamp?

Any help is greatly appreciated.

+3


source to share


1 answer


Have you tried using django-qsstats-magic (https://github.com/kmike/django-qsstats-magic)?

This is very handy for charting, here is an example timing from their docs:



from django.contrib.auth.models import User
import datetime, qsstats

qs = User.objects.all()
qss = qsstats.QuerySetStats(qs, 'date_joined')

today = datetime.date.today()
seven_days_ago = today - datetime.timedelta(days=7)

time_series = qss.time_series(seven_days_ago, today)
print 'New users in the last 7 days: %s' % [t[1] for t in time_series]

      

+3


source







All Articles