2012-04-02 37 views
0

嗨MySQL查询或同等学历我有一个查询,这是非常简单的在mysql中写的,但我有困难翻译成Django的:使用在Django

SELECT year, month, AVG(mean_air_temp), AVG(min_air_temp), AVG(max_air_temp) from climate WHERE recorded_on >= '1978-09-09' AND recorded_on <= '1988-09-09' GROUP by month; 

我的数据是这样的:

+----+------+-------+-------------+---------------+--------------+--------------+----------+--------------+---------------+ 
| id | year | month | recorded_on | mean_air_temp | min_air_temp | max_air_temp | sea_temp | mean_rel_hum | precipitation | 
+----+------+-------+-------------+---------------+--------------+--------------+----------+--------------+---------------+ 
| 1 | 1964 | 12 | 1964-12-31 |   26.1 |   22.2 |   30.8 |  25.8 |   82 |    0 | 
| 2 | 1965 |  1 | 1965-01-01 |   23.9 |   21 |   25.8 |  22.7 |   84 |   0.7 | 
| 3 | 1965 |  1 | 1965-01-02 |   23.4 |   21.1 |   26.2 |  22.4 |   83 |    0 | 

我基本上是试图以最有效的方式按月取得平均值,并用另一个查询按年取得平均值。平均的字段将是视图中的python变量,日期和按方法分组也是如此。

是否有本机Django解决方案,还是我需要使用.extra()做些什么(尽管我想避免这种情况,所以我没有绑定到mysql)?我查看了aggregate的文档,但在这种情况下他们并没有帮助。

任何帮助将非常感激。

回答

1

你试过:

from django.db.models import Count 
from django.db.models import Avg, Max, Min, Count 


un_test_able = Climate.objects.filter(
          recorded_on__gte='1978-09-09', 
          recorded_on__lte='1988-09-09') 
         .values('month') 
         .annotate(mean_air_temp=AVG('mean_air_temp'), 
           min_air_temp=AVG('min_air_temp'), 
           max_air_temp=AVG('max_air_temp') 
        ) 

动力版本,不知道你需要怎样动态的,但你可以建立一个关键字ARG字典,只要你喜欢,并把它传递给注释功能。

例1动态密钥...

key_mean = 'mean_air_temp' 
query_value_mean='mean_air_temp' 
kwargs = { 
      key_mean:AVG(query_value_mean), 
      'min_air_temp':AVG('min_air_temp'), 
      'max_air_temp':AVG('max_air_temp') 
} 
un_test_able = Climate.objects.filter(
          recorded_on__gte='1978-09-09', 
          recorded_on__lte='1988-09-09') 
         .values('month') 
         .annotate(**kwargs) 
        ) 
+0

想要用'annotate'指定名称。 – agf 2012-04-02 21:16:23

+0

@Nix - 非常感谢。这似乎是在正确的轨道上! – 2012-04-02 21:39:23

+0

还有一个问题 - 如果我需要动态注释查询 - 我该如何实现这一点?也就是说,如果我不知道提前查询哪些参数,我该如何添加这些子句来即时注释? – 2012-04-02 21:49:03