我现在正在处理表单逻辑,我的任务听起来很简单——我需要实现具有相关字段的表单: 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 queryset 取决于所选的 Region,而 Region queryset 取决于所选的 Country。我将我的逻辑放在 init 表单方法中,它看起来像这样:
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'])
但它不起作用并引发错误:
“无法将关键字‘country’解析到字段中。选择是:id、name、region..”
问题是:
有没有办法只按所选国家(不选择地区)过滤我的地区查询集?
我(在脑海中)想象这像 self.fields['district'].queryset.filter('region'=[1,2,3])
- 但我无法过滤字段查询集通过具有多个值的列表。希望有人能帮助我找到一种正确的方法来按国家/地区过滤我的地区。
最佳答案
你可以通过列出所有用双下划线连接的关系来遍历更多的关系,
例如'地区' + '__' + '国家'
。无法从地区直接访问国家/地区,而只能通过模型中的地区访问。
self.fields['district'].limit_choices_to = {'region__country': self.data['country']}
关于python - 通过遍历多个关系(外键到外键?)来过滤 Django 表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62452142/