Search code examples
djangodjango-modelsforeign-keysdjango-smart-selects

How to limit ForeignKey field to another model FK depending on value


I have the following models in Django, and using smart-selects:

class Country(models.Model):
    name = models.CharField(max_length=100)

class Province(models.Model):
    name = models.CharField(max_length=100)
    country = models.ForeignKey(Country)

class City(models.Model):
    name = models.CharField(max_length=100)
    country = models.ForeignKey(Country)
    province = models.ForeignKey(Province)

In the fixtures, i added multiple countries, with their provinces, and cities.

I'm using smart-selects for chaining in this model

class WorkArea(models.Model):
    work_area = models.CharField(max_length=100)
    country = models.ForeignKey(Country)
    province =  ChainedForeignKey(Province, chained_field="country",chained_model_field="country")
    city = ChainedForeignKey(City, chained_field=province", chained_model_field="province")

Now i have this model:

class Project(models.Model):
    project_name = models.CharField(max_length=100)
    province = models.ForeignKey(Province)

The question: In the model Project how do i show only provinces form Province model, that has country set to X (If i have countries "USA" and "Canada" i want the field province to show list of provinces in "USA" only, with preselecting country).


Solution

  • This is the solution using limit_choices_to

    class Project(models.Model):
        project_name = models.CharField(max_length=100)
        province = models.ForeignKey(Province, limit_choices_to={"country": 1})