2016-07-05 121 views
2

我有這樣的一些鏈接外鍵關係:創造Django管理鏈表外鍵

class Continent(models.Model): 
    continent = models.CharField(max_length=30) 

class Country(models.Model): 
    country = models.CharField(max_length=30) 
    continent = models.ForeignKey(Continent) 

class City(models.Model): 
    city = models.CharField(max_length=30) 
    country = models.ForeignKey(Country) 

class Person(models.Model): 
    name = models.CharField(max_length=30) 
    continent = models.ForeignKey(Continent) 
    country = models.ForeignKey(Country) 
    city = models.ForeignKey(City) 

,並在人管理員創建新項目的看法,我想國家和城市的名單被改變基於選擇什麼大陸等 我試過LinkedSelect of django suit,但我認爲這並不意味着這一點。 我讀了一下django select2,但是我沒有看到任何支持。 任何想法是否有一個可以提供幫助的軟件包?


更新:我碰到this

這表明Django的聰明選擇。我嘗試過這個。有兩個問題: - 它需要你修改模型,這是一個紅色標誌。 - 它以類別的形式顯示列表,但仍允許您選擇不合意的錯誤項目。 (show_all不適用於GroupedForeignKey)

我有一個好主意。因爲我想用Django的自動完成光,如果我可以添加一個事件處理程序,說當你選擇第一個列表中使用自動完成,然後修改第二個列表的自動完成URL中附加參數傳遞,那麼整個鏈條會工作。我堅持的是當我更改url(data-autocomplete-light-url)時,它不起作用。我不知道如何觸發它重新加載。

回答

1

幸運的是,這其實是part of django-autocomplete-light

您必須創建自己的表單(如果尚未完成):

class PersonForm(forms.ModelForm): 

    class Meta: 
     model = Person 
     fields = ('__all__') 
     widgets = { 
      'country': autocomplete.ModelSelect2(url='country-autocomplete' 
               forward=['continent']), 
      'city': autocomplete.ModelSelect2(url='city-autocomplete' 
               forward=['country']), 
     } 

更新您自動完成:

class CountryAutocomplete(autocomplete.Select2QuerySetView): 
    def get_queryset(self): 
     if not self.request.is_authenticated(): 
      return Country.objects.none() 

     qs = Country.objects.all() 

     continent = self.forwarded.get('continent', None) 

     if continent: 
      qs = qs.filter(continent=continent) 

     if self.q: 
      qs = qs.filter(country__istartswith=self.q) 

     return qs 

class CityAutocomplete(autocomplete.Select2QuerySetView): 
    def get_queryset(self): 
     if not self.request.is_authenticated(): 
      return City.objects.none() 

     qs = City.objects.all() 

     country = self.forwarded.get('country', None) 

     if country: 
      qs = qs.filter(country=country) 

     if self.q: 
      qs = qs.filter(city__istartswith=self.q) 

     return qs 

並使用新的形式在您的ModelAdmin:

class PersonAdmin(admin.ModelAdmin): 
    form = PersonForm 
+0

它很好用!謝謝。 – max