Filtering Django form fields by traversing more than one relationship (foreign key to foreign key?)

Viewed 168

I am working with form logic now and my task sounds pretty easy - I need to implement form with dependent fields: 1) Country 2) Region 3) District (area)

So I have my simple models:

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)

It means that District queryset is depends on chosen Region and Region queryset is depends on chosen Country. I put my logic in the init form method and it looks like this:

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 it doesn’t works and raises an error: "Cannot resolve keyword 'country' into field. Choices are: id, name, region.." The question is: Is there a way to filter my district queryset by chosen country only (without chosen region)? I picture this (in my head) like self.fields['district'].queryset.filter('region'=[1,2,3]) - but I can't filter field queryset by list with multiple values. Hope someone will help me to find a proper way to get my districts filtered by country.

1 Answers

You can traverse more relationships by listing them all connected by double underscore,
e.g. 'region' + '__' + 'country'. Country is not directly accessible from district, but only via region in your model.

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