我的模型叫Plan
计划与state
和city
相关联
我还有其他名为Weather
的模型,其中city
state
每天都有不同时间的数据
现在我想要使用名为weather的额外字典来获取所有Plan对象。
步骤
20 , 21 , 22 , 23 , 24
。那么我想把所有温度的平均值,即22并存储在计划模型中的新词典这样我就可以访问Plan.weather.temperature
了22
我可以使用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)')
答案 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无法促进这一点(似乎是开箱即用的强大候选者),那么您可以选择编写原始查询: