如何使用具有分组,平均和“IN”的Django模型创建查询

时间:2017-09-08 16:24:24

标签: python django django-models

有谁知道如何构建这样的原始查询:

SELECT week_number, part, type,  AVG(col1), AVG(col2), AVG(col3), ( AVG(col1) + AVG(col2) + AVG(col3) ) as Total
FROM table1
WHERE location = 'TgR'
AND week_number BETWEEN 38 AND 42
AND part IN ('Q', 'F')
GROUP BY week_number, part, type

在Django模型中?完全不知道该怎么做

我的模特:

class testTable(models.Model):
    date = models.DateField( verbose_name="Date" )
    week_number = models.CharField(max_length=2, verbose_name="Week number")
    location = models.CharField(max_length=10, verbose_name="Location")
    part = models.CharField(max_length=10, verbose_name="Part")
    col1 = models.CharField(max_length=20, verbose_name="Col1")
    col2 = models.CharField(max_length=20, verbose_name="Col2")
    col3 = models.CharField(max_length=20, verbose_name="Col3")

    def __unicode__(self):
        return str(self.location)+'-'+str(self.date)+'-'+str(self.part)

提前致谢,

1 个答案:

答案 0 :(得分:0)

from django.db.models import Avg
from django.db.models import FloatField
query_set=testTable.objects.filter(location='TgR',\
          part__in=['Q', 'F'],week_number__lte=38,week_number__gte=42).\
          aggregate(col1_avg=Avg('col1'),col2_avg=Avg('col2'),col3_avg=Avg('col3'),\
          Total= (Avg('col1',output_field=FloatField())+Avg('col2', output_field=FloatField())+Avg('col3', output_field=FloatField()))
         )

从上面的查询集中,您可以获取值,也可以参考文档source