[Answer]-Django model – set up a "has_many_through" relationship

1👍

Take a look at ForeignKey.limit_choices_to.

This allows you to filter the available choices and is enforced in ModelForm. Since you already have the company foreign key in your Job model, you should be able to use that to filter the choices.

0👍

I ended up using https://github.com/digi604/django-smart-selects and wrote the model like this. I don’t think limit_choices_to works in this case (according to other SO threads)

from smart_selects.db_fields import ChainedForeignKey 

class Company(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField()

class Location(models.Model):
    is_primary_location = models.BooleanField()
    address = models.CharField(max_length=200)
    company = models.ForeignKey(Company)

class Job(models.Model):
    title = models.CharField(max_length=200)
    company = models.ForeignKey(Company)
    location = ChainedForeignKey(
        Location,
        chained_field="company",
        chained_model_field="company",
        show_all=False,
        auto_choose=True
    )

Leave a comment