Django model with 2 foreign keys from the same table Django model with 2 foreign keys from the same table django django

Django model with 2 foreign keys from the same table


I haven't done this yet, but I used inspectdb to generate the models.py file from an existing DB that does exactly that - this is what inspectdb threw back, so it should work:

creator = models.ForeignKey(Users, null=True, related_name='creator')assignee = models.ForeignKey(Users, null=True, related_name='assignee')

Hope that works for you - if it doesn't I am going to have a problem too.


From the error message, it sounds like you're trying to put two foreign keys to the same object on an intermediary table used via the through argument to ManyToManyField, the documentation for which states:

When you set up the intermediary model, you explicitly specify foreign keys to the models that are involved in the ManyToMany relation. This explicit declaration defines how the two models are related.

There are a few restrictions on the intermediate model:

  • Your intermediate model must contain one - and only one - foreign key to the target model (this would be Person in our example). If you have more than one foreign key, a validation error will be raised.
  • Your intermediate model must contain one - and only one - foreign key to the source model (this would be Group in our example). If you have more than one foreign key, a validation error will be raised.