Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to have a multiple foreign keys references the same table in one table

I know that normally Django would create a foreign key called user_id if I simply do something like

from django.db import models

class Order(models.Model):
    user = models.ForeignKey(User)
    comments = models.CharField(max_length=400)
    date_created = models.DateTimeField('created date')

class User(models.Model):
    name = models.CharField(max_length=200)
    age = models.IntegerField()

but what if I need three distinct foreign key in Order that all points to User? The three foreign keys would be user_created, user_modified, and user_status.

like image 705
hobbes3 Avatar asked Feb 24 '12 22:02

hobbes3


People also ask

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 I have multiple foreign keys in a table Django?

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 two foreign keys in the same table reference the same primary key?

Yes, it is okay to have two fk to the same pk in one table.

Can a table have more than one foreign key defined?

The FOREIGN KEY constraint differs from the PRIMARY KEY constraint in that, you can create only one PRIMARY KEY per each table, with the ability to create multiple FOREIGN KEY constraints in each table by referencing multiple parent table.


1 Answers

The solution is actually straight forward:

class Order(models.Model):
    user_status = models.ForeignKey(User, related_name='orders_status')
    user_created = models.ForeignKey(User, related_name='orders_created')
    user_modified = models.ForeignKey(User, related_name='orders_modified')

You just need to define separate related_names to avoid ambiguity when accessing the Order from the User object.

like image 172
alex Avatar answered Sep 18 '22 17:09

alex