Search code examples
djangomodelforeign-keyslimit-choices-to

limit_choices_to within Django model


I have a project model. This project contains persons (those who are working on the project). I am trying to also make a model for each project person, including any notes they have on the project and % complete on project.

My issue is that I want to filter the individual_person_in_project to only the persons within the corresponding project. I am trying to use

limit_choices_to = {'person_in_project':User}

I want to limit my choices to users who are persons in my Project model.

class Project(models.Model):
    project_name = models.CharField(max_length = 120,null = False,blank = False)
    project_percent_complete = models.IntegerField(blank = True,null = True, default = 0)
    person_in_project = models.ManyToManyField(User,related_name = 'project_person',blank = True)
    project_description = models.CharField(max_length = 300,null = True,blank = True)

class Project_Person(models.Model):
    corresponding_project = models.ForeignKey(Project,related_name = 'corresponding_project_this_user_is_in',null = False)
    individual_person_in_project = models.ForeignKey(User, related_name = 'a_person_within_the_corresponding_project', limit_choices_to = {'person_in_project':User})
    percent_complete = models.IntegerField(default = 0)

Solution

  • I left a comment above, but I think this is a better answer, anyhow:

    You can use the through option to track extra information on the manytomanyfield, so you get:

    class Project(models.Model):
        ...
        person_in_project = models.ManyToManyField(User, related_name='project_person', blank=True, through=ProjectPerson)
    

    The docs explain the rest of the details, but you shouldn't have to handle the limit_choices_to in that case.