2017-03-01 3 views
-1

私はこの2つのモデルを持っています。Djangoは高度なjoin/queryを使用して、外部キーをフィルタリングする方法は?

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

各都市は、1つの言語で複数の翻訳された名前を持つことができます。

だから私は国= "ポーランド"のすべての都市を取得したいと思います。対応する都市にlang = nameの1つ以上のCityTranslationsがある場合。私はprioによって最初に注文されたものだけを入手したい。

私は今のようなことをしています。

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

しかしので、これは、機能していません:市がCityTranslationなしがある場合、それは

  • 記載されていることがしたい

    1. 複数CityTranslation年代がある場合、それらすべてが表示されます。しかし、私はちょうど最初にしたい。 (...).ordered_by( 'prio')。first())

    ご存じですか?

    EDIT:

    @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を設定する必要があるかもしれません: はPRIOで私のCityTranslationを注文すると、最初の1をピックアップさ@propertyフィールドを使用して、それを解決しました。

    IDで注文する予定がある場合は、orderbyは必要ありません。

    関連する問題