[Answered ]-Django How to organize models so there is only one owner

1๐Ÿ‘

โœ…

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].

Leave a comment