Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model with 2 foreign keys from the same table

I wanted a Django model with 2 foreign keys from the same table. It's an event table which has 2 columns for employees: the 'actor' and the 'receiver'. But I get this error:

Error: One or more models did not validate: tasks.task: Intermediary model TaskEvent has more than one foreign key to Employee, which is ambiguous and is not permitted.

Is there a better way to model this?

I think I'm going to add a TaskEvent_to_Employee table. There will be two records in it, one for each of the two employees related to each TaskEvent. Does anyone know an easier workaround?

like image 965
Josh Avatar asked Feb 24 '09 20:02

Josh


People also ask

Can a Django model have 2 foreign keys?

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.

Can 2 foreign keys reference the same table?

In scenarios where a table can have relationships with multiple other tables, you will need to add multiple foreign keys to a table. For the Employee table, you need to add foreign keys that reference the primary keys of the Department table and the Insurance table.

Can a class have 2 foreign keys?

Foreign Key ColumnsA single column can have multiple foreign key constraints. For an example, see Add multiple foreign key constraints to a single column.

Can an object have multiple foreign keys?

Yes, that makes perfect sense. It is not at all uncommon to have a table with multiple foreign keys to other tables.


Video Answer


1 Answers

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.

like image 164
Technical Bard Avatar answered Sep 24 '22 17:09

Technical Bard