Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Two way one-to-one relationship. Chick or egg?

What is the appropriate way to create an instance of the following two models

class Administrator(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    account = models.ForeignKey(Account)

class Account(models.Model):
    owner = models.OneToOneField(Administrator)

Both require each other. An account cannot exist without a primary user (owner), and an administrator (which is what owner is) cannot exist without an account. Yes a general User object can exist on it's own but I can't wrap my brain around which of these should come first and how to implement that correctly. If I have to use blank=True on Administrator's account attribute I will, but is there a better way? Should I use a transaction to ensure one cannot exist without the other?

like image 582
orokusaki Avatar asked Oct 17 '25 10:10

orokusaki


1 Answers

If two models exist such that each requires the other, they should usually be combined into a single model.

In any case there is probably a better way to structure the classes. Personally I would construct a UserProfile class as follows:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    administrator = models.BooleanField()

or possibly:

class UserProfile(models.Model):
    user = models.OneToOneField(User)

class AdministratorProfile(UserProfile):
    # attributes

or even:

class UserProfile(models.Model):
    user = models.OneToOneField(User):

class AdministratorProfile(models.Model):
    profile = models.OneToOneField(UserProfile)

any of these methods should work.

like image 171
Marcus Whybrow Avatar answered Oct 21 '25 08:10

Marcus Whybrow