Artem
Artem

Reputation: 132

Django How to organize models so there is only one owner

I have two models Company and User:

class Company(models.Model):
    name = CharField("Name", max_length=60)
    owner = OneToOneField(
        "Employee", related_name='owner', on_delete=SET_NULL, null=True)

class BaseUser(AbstractBaseUser, PermissionsMixin):

    objects = CustomUserManager()

    join_date = DateTimeField(default=timezone.now)
    name = CharField("Name", max_length=60)
    email = EmailField(('Email'), unique=True)
    company = ForeignKey(Company, on_delete=models.CASCADE)

I need to have only one User as owner. I made it so two models point to each other which doesn't seem right. Is there a way to fix it and still have only one possible owner? I know standard way would be to add is_owner = Boolean to User but it allows other Users to be owners.

Upvotes: 1

Views: 300

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477200

A ForeignKey from the Company to the BaseUser is sufficient:

class Company(models.Model):
    name = CharField("Name", max_length=60)
    owner = ForeignKey(
        'Employee',
        related_name='companies'
    )

class BaseUser(AbstractBaseUser, PermissionsMixin):
    objects = CustomUserManager()
    join_date = DateTimeField(default=timezone.now)
    name = CharField("Name", max_length=60)
    email = EmailField(('Email'), unique=True)
    # no company

Here we thus link a Company to one user. Two Companys can have the same owner, and it is possible that the BaseUser has no, one, or more Companys where he is the owner.

You can obtain all the companies for which a BaseUser is the owner with:

myuser.companies.all()

If two companies should always point to two different users, you can make use of the OneToOneField [Django-doc].

Upvotes: 1

Related Questions