Django: One-to-One Bilateral Relations. Chicken or Egg?

How 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 (as it is owner) cannot exist without an account. Yes, a common user object can exist by itself, but I can’t wrap my brain around which one should be the first, and how to implement it correctly. If I have to use blank = True in the admin account attribute, I will, but is there a better way? Should I use a transaction to ensure that it cannot exist without the other?

+3
source share
2 answers

If there are two models, each of which requires the other, they should usually be combined into one model.

In any case, probably the best way to structure classes. Personally, I would build the class UserProfileas follows:

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

or perhaps:

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.

+4
source

I'm not quite sure that I fully understand the differences between Administrator, Accountand contrib.auth.User,

This is similar to the is-a vs. discussion It seems that Administrator- User (indeed, UserProfile, for reasons specific to django), but the administrator has one Account. Accounts have nothing, because they cannot own and be own.

. , . , , - , .

0

Source: https://habr.com/ru/post/1733573/


All Articles