开发者

Aggregating data in a single table with Django

开发者 https://www.devze.com 2023-01-27 14:00 出处:网络
Using Django, I want to generate a queryset with some daily statistics by aggregating from a table with multiple entries per day.Here\'s the table

Using Django, I want to generate a queryset with some daily statistics by aggregating from a table with multiple entries per day. Here's the table

CREATE TABLE weather
(
  id serial NOT NULL,
  air_temp double precision NOT NULL,
  obs_date date,
  ....
)

This is the SQL equivalent of the result I want to get this in the queryset

select obs_date, avg(air_temp) from weather group by obs_date order by obs_date

The Django model looks like this

class WeatherData(models.Model):

    obs_date = models.DateField('Obs Date', blank=False, null=False, db_index=True)
    air_temp = models.Flo开发者_运维知识库atField('Air Temp', blank=False, null=False)
    ...

I've read this http://docs.djangoproject.com/en/dev/topics/db/aggregation/ but can't see how to do it. Suggestions appreciated.

Update: this works:

WeatherData.objects.values('obs_date').annotate( max_air=Max('air_temp'), min_air=Min('air_temp'))


somedata = WeatherData.objects.annotate(Avg('air_temp')).order_by('obs_date')
for datum in somedata:
  print '%s: %s' % (datum.obs_date, datum.air_temp__avg)
0

精彩评论

暂无评论...
验证码 换一张
取 消