[英]Filtering Django form fields by traversing more than one relationship (foreign key to foreign key?)
我現在正在使用表單邏輯,我的任務聽起來很簡單 - 我需要使用相關字段來實現表單:1)國家 2)地區 3)區(地區)
所以我有我的簡單模型:
class CountryModel(models.Model):
name = models.CharField('Country name', unique=False, max_length=128, blank=False, null=False)
class RegionModel(models.Model):
name = models.CharField('Region name', unique=False, max_length=128, blank=False, null=False)
country = models.ForeignKey(CountryModel, on_delete=models.CASCADE, blank=True, null=True)
class DistrictModel(models.Model):
name = models.CharField('District name', unique=False, max_length=128, blank=False, null=False)
region = models.ForeignKey(RegionModel, on_delete=models.CASCADE, blank=True, null=True)
class FormModel(models.Model):
country = models.ForeignKey(CountryModel, on_delete=models.CASCADE, blank=True, null=True)
region = models.ForeignKey(RegionModel, on_delete=models.CASCADE, blank=True, null=True)
area = models.ForeignKey(AreaModel, on_delete=models.CASCADE, blank=True, null=True)
這意味着 District 查詢集取決於所選的 Region,Region 查詢集取決於所選的 Country。 我把我的邏輯放在初始化表單方法中,它看起來像這樣:
class SignCreateForm(ModelForm):
data_url = '/sign-form-data/'
class Meta:
model = FormModel
fields = ['country', 'region', 'district']
dependencies = {'district': ('region', 'country'), 'region': ('country',)}
class Media:
# ajax form refreshing script
js = ('js/formset.js',)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.is_bound:
if self.data['country']:
self.fields['district'].limit_choices_to = {'country': self.data['country']}
apply_limit_choices_to_to_formfield(self.fields['district'])
Dut 它不起作用並引發錯誤: "Cannot resolve keyword 'country' into field. Choices are: id, name, region.."
問題是:有沒有辦法僅按所選國家/地區過濾我的地區查詢集(沒有選擇區域)? 我(在我的腦海中) self.fields['district'].queryset.filter('region'=[1,2,3])
- 但我無法通過具有多個值的列表過濾字段查詢集。 希望有人能幫助我找到一種正確的方法來按國家過濾我的地區。
你可以通過雙下划線列出它們來遍歷更多的關系,
例如'region' + '__' + 'country'
。 Country 不能從地區直接訪問,而只能通過 model 中的地區訪問。
self.fields['district'].limit_choices_to = {'region__country': self.data['country']}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.