0

I have the a ForeignKey field on the User model.

company = models.ForeignKey('crm.Company')

So every user needs to have a company.

The problem is the create_super_user method does not have a company at the start of a project and I get the following error:

django.db.utils.OperationalError: (1054, "Unknown column 'users_user.company_id' in 'field list'")

So would it be best to just create a default Company and assign it with get_or_create like:

def create_superuser(self, email, password, **kwargs):
    company, created = Company.objects.get_or_create(
        name='Default Company',
    )
    kwargs.setdefault('company', company)
    kwargs.setdefault('is_staff', True)
    kwargs.setdefault('is_superuser', True)
    kwargs.setdefault('is_active', True)

    if kwargs.get('is_staff') is not True:
        raise ValueError('Superuser must have staff=True')
    if kwargs.get('is_superuser') is not True:
        raise ValueError('Superuser must have is_superuser=True')
    return self.create_user(email, password, **kwargs)

The problem may arise when I create a new superuser from command line and the Default company has changed. Now a new Default Company will be created.

On the other hand I can make the company field optional with null=True but now that breaks the system rules that each user is associated to a company.

How else can I ensure a company has been created already?

tread
  • 10,133
  • 17
  • 95
  • 170

1 Answers1

2

You can add BooleanField to the company model:

is_default = BooleanField(default=False)

Now in create_superuser you can search company by this field. You can use defaults argument of get_or_create to set new company name in case of default company does not exists:

company, created = Company.objects.get_or_create(
    is_default=True, 
    defaults={'name': 'Default Company'}
)
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100