2017-03-01 71 views
-1

我有這兩個模型。Django高級加入/查詢,如何過濾外鍵?

class City(models.Model): 
    city = models.CharField(max_length=200) 
    country = models.CharField(max_length=200) 

class CityTranslation(models.Model): 
    city = models.ForeignKey(City) 
    name = models.CharField(max_length=200) 
    lang = models.CharField(max_length=2) 
    prio = models.IntegerField() 

每個城市在一種語言中可以有多個翻譯過的名字。

所以我想讓所有城市的國家=「波蘭」。如果相應的城市有一個或多個lang = name的CityTranslations。我只想得到prio訂購的第一個。

我現在正在做類似的事情。

City.objects.filter(country="Poland", citytranslation__land="pl").annotate(transname=F("alt_names__name")) 

但是,這是不工作的,因爲:

  1. 如果有一個城市沒有它想上市
  2. 如果有多個CityTranslation的他們都將顯示一個CityTranslation。但我只想要第一個。 (... .ordered_by('prio')。first())

任何想法?

編輯: 使用@property場,這是由排序我PRIO和CityTranslation挑選的第一個解決了這個問題:

@propert 
def transcity(self): 
    return self.citytranslation.filter(lang="pl").order_by('-prio').first() 

回答

0
def magic(passed_country="Poland", passed_lang="pl") 
    # I want to get all City's with country="Poland". 
    cities = City.objects.filter(country=passed_country) 

    # If a corresponding City has one or more CityTranslations with lang=name. I want to get only the first ordered by prio. 
    suitable_cities = cities.filter(citytranslation__lang=passed_lang) 
    if suitable_cities.exists() 
     first_matching_city = suitable_cities.orderby('prio').first() 
    else: 
     first_matching_city = cities.orderby('prio').first() 

    return first_matching_city 

可能需要設立一個citytranslation relatedname。

可能不需要orderby,如果你打算通過ID訂購反正。