【问题标题】:Filtering Django form fields by traversing more than one relationship (foreign key to foreign key?)通过遍历多个关系(外键到外键?)过滤 Django 表单字段
【发布时间】:2020-10-08 15:18:52
【问题描述】:

我现在正在处理表单逻辑,我的任务听起来很简单——我需要使用依赖字段来实现表单: 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。我把我的逻辑放在 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'])

Dut 它不起作用并引发错误: "Cannot resolve keyword 'country' into field. Choices are: id, name, region.." 问题是: 有没有办法仅按所选国家(不包括所选地区)过滤我的地区查询集? 我把这个(在我的脑海里)想象成self.fields['district'].queryset.filter('region'=[1,2,3]) - 但我不能通过具有多个值的列表过滤字段查询集。希望有人能帮助我找到一种正确的方法来按国家过滤我的地区。

【问题讨论】:

    标签: python django forms filter django-queryset


    【解决方案1】:

    您可以通过将它们全部用双下划线列出来遍历更多关系,
    例如'region' + '__' + 'country'。 Country 不能从地区直接访问,而只能通过模型​​中的地区访问。

    self.fields['district'].limit_choices_to = {'region__country': self.data['country']}
    

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 1970-01-01
      • 2018-08-28
      • 2013-07-20
      • 2015-12-20
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多