繁体   English   中英

如何在django python中加入两个表的结果

[英]How to join the results of two tables in django python

我有两个型号

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)')

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

为每个地区和地区提供独特的排。 我想结合结果,以便我可以获得两个表的所有列

这两个模型彼此无关。 '我需要像这样加入

join weather w on w.region = A.region and w.distric = A.district

所以结果包含每个对象中的所有列

obj.temp_max等

w = Weather.objects.get(pk=1)
w.region.plan.name
w.district.plan.name
w.temp_max
w.temp_min

w.region是链接的区域行,因此可以通过它访问区域模型中的任何属性。 因此,如果您的区域模型有name ,您可以使用w.region.name ,它与w.district相同。

w.region.plan是计划表中的一行,该行具有链接到主要键为1的天气对象的区域行的外键; w.district.plan工作方式相同。


我必须显示的数据是计划。 所以我想从计划到天气。 不是从天气到计划。 我不认为我可以去plan.region.weather.temp_max,因为一个地区会有很多行,我想过滤区域和地区的汇总

p = Plan.objects.get(pk=1) # get a Plan
p.region.weather_set.all() # all "weathers" for the region for this plan
p.district.weather_set.all() # all "weathers" for the district for this plan

过滤:

plans = Plan.objects.filter(region__name='Region 1') # all plans for that region
for plan in plans:
   region_weather = plan.region.weather_set.all()
   district_weather = plan.district.weather_set.all()

如果我有多行,有没有办法聚合e,g温度。 即我有两个相同地区和地区的天气,我想要平均值

是的,请阅读有关聚合的文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM