2012-11-01 25 views
0

我有兩個型號如何加入兩個表的結果,Django的蟒蛇

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

,這樣的結果包含everyobject所有列像

obj.temp_max等

回答

2
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會有很多行的 一個區域,我想對區域和地區的comination

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的溫度。即我有同樣的區域和 區兩級天氣enteries和我想的平均

是,閱讀文檔上aggregation

+0

如果我有多行,是否有任何方法來聚合e,g溫度。即我有兩個天氣enteries相同的地區和地區,我想avg – user825904

+0

我也必須顯示的數據是爲計劃。所以我想從計劃走向天氣。不是從天氣到計劃。我不認爲我可以去'plan.region.weather.temp_max',因爲一個地區會有很多行,我想過濾地區和地區的聯合 – user825904