7

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.

hobbes3
  • 28,078
  • 24
  • 87
  • 116
  • Possible duplicate of [How can I have two foreign keys to the same model in Django?](https://stackoverflow.com/questions/543377/how-can-i-have-two-foreign-keys-to-the-same-model-in-django) – Aaron McMillin Aug 14 '17 at 14:32

1 Answers1

15

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.

frlan
  • 6,950
  • 3
  • 31
  • 72
alex
  • 1,229
  • 7
  • 6
  • Ok, so your `user` in this case would be `user_status`? Is there a reason why you don't use `related_name` for the first one? – hobbes3 Feb 24 '12 at 22:26
  • The first one takes the default related name and is accessed via `user.order_set` - of course, one could also assign a custom related name here as well. – alex Feb 24 '12 at 22:31
  • ...and yes, the first one would be user_status - I overlooked it in your post and updated my answer – alex Feb 24 '12 at 22:33