[Fixed]-Django junction table with extra foreignkey

1👍

Assuming you define the many to many relationship this way in the Project model:

workers = ManyToManyField(Worker)

Assuming you have a model form named ProjectForm to create or modify projects. You can define a clean function in this form:

def clean(self):
    cleaned_data = super(ProjectForm, self).clean()
    for w in cleaned_data['workers']:
        if w.company.id != cleaned_data['company'].id:
              self.add_error('workers', your_error_message)
              break
    return cleaned_data

Hope this help.

👤albar

Leave a comment