如何在django python中进行这个复杂的查询

时间:2012-11-01 03:27:15

标签: python django

我的模型叫Plan

计划与statecity相关联

我还有其他名为Weather的模型,其中city

中的每个state每天都有不同时间的数据

现在我想要使用名为weather的额外字典来获取所有Plan对象。

步骤

  1. 获取所有计划对象
  2. 现在根据州和城市,每个计划在气象表中会有很多行
  3. 我希望聚合所有列。例如,如果我有五行用于该城市和州 温度值为20 , 21 , 22 , 23 , 24。那么我想把所有温度的平均值,即22并存储在计划模型中的新词典
  4. 这样我就可以访问Plan.weather.temperature22

    我可以使用for循环但这将是很多数据库查询。可以在一个查询上执行此操作,或者可以选择哪种选项

    编辑:

    class Plan(model.model):
        name = tinymce_models.HTMLField(blank=True, null=True)
        region = models.ForeignKey(Region)
        district = models.ForeignKey(District)
    

     class Weather(model.model):
    
            region = models.ForeignKey(Region)
            district = models.ForeignKey(District)
            temp_max = models.IntegerField(blank=True, null=True, verbose_name='Max temperature (C)')
            temp_min = models.IntegerField(blank=True, null=True, verbose_name='Min temperature (C)')
    

1 个答案:

答案 0 :(得分:2)

取决于你的模型,但是这样:

Plan.objects.filter(region__name="CA").annotate(avg_temperature=Avg("region__weather__temp_max"))

avg_temperature字段现在可用于查询返回的对象。此名称可根据提供给注释的关键字参数进行自定义。

或者看看这里:https://docs.djangoproject.com/en/dev/topics/db/aggregation/

Django内置了这些类型的查询。如果聚合和注释api无法促进这一点(似乎是开箱即用的强大候选者),那么您可以选择编写原始查询:

https://docs.djangoproject.com/en/dev/topics/db/sql/