Automatic tenant name generation in django

A bit of preface first. I'm building a multi-tenant consumer facing application using Django/DRF. I'm (trying) not to use any 3rd party package for the multi-tenancy part. Instead I simply made a Tenant model that has a OneToOne field in the User model, so that there is a main tenant's table where all other tables have a foreign key pointing to it.

Something like this:

class Tenant(models.Model):
    tenant_id = f'{models.UUIDField(primary_key=True, default=RandomUUID, editable=False)}'
    tenant_name = models.CharField(max_length=255, default=get_user_email()) # How?


class UserAccount(AbstractBaseUser, PermissionsMixin):
    tenant = models.OneToOneField(Tenant, on_delete=models.CASCADE)
    user_id = f'{models.UUIDField(primary_key=True, default=RandomUUID, editable=False)}'
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    email = models.EmailField(unique=True, max_length=255)

So then I tried to create function in models.py in the Tenant app that would return the user's email and then use that as a callable for a default value in tenant_name like so:

from users.models import UserAccount

def get_user_email():
    return UserAccount.user.email

class Tenant(models.Model):
    tenant_id = f'{models.UUIDField(primary_key=True, default=RandomUUID, editable=False)}'
    tenant_name = models.CharField(max_length=255, default=get_user_email())

But when I go to run makemigrations, it tells me that it cannot import UserAccount from user.models (most likely due to a circular import).

So,

  1. am I on the right track?
  2. How do I avoid circular imports?
Back to Top