I have created a Company model and a profile model.
Every User belongs to one company and a company can belong to many users.
Which of the two is the correct way of modelling it?
class Company(models.Model):
company_name = models.CharField(max_length=50)
company_code = models.CharField(max_length=40)
company_email = models.EmailField()
def save(self, *args, **kwargs):
if not self.company_code:
self.company_code = uuid.uuid1()
super(Company, self).save(*args, **kwargs)
Now the UserProfile is defined like this:
class UserProfile(models.Model):
# This field is required.
user = models.OneToOneField(User)
# Other fields here
company = models.ManyToManyField(Company)
# !!!! OR !!!!
company = models.ForeignKey(Company)
Update:
class UserProfile(models.Model):
user = models.OneToOneField(User)
company = models.ForeignKey(Company)
def create_user_profile(self, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
I have now added this bit to UserProfile class also added AUTH_PROFILE_MODULE = 'MyApp.UserProfile' to the settings.
When I do syncdb I get an error message:
>> company = models.ForeignKey(Company)
NameError: name 'Company' is not defined
A
ManyToManyFieldwould allow aUserto belong to multipleCompanys. Based on your spec aForeignKeywould be appropriate.