我创建了公司模型和个人资料模型。
每个用户都属于一个公司,公司可以属于许多用户。
这两个中哪一个是正确的建模方式?
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)
现在UserProfile的定义如下:
class UserProfile(models.Model):
# This field is required.
user = models.OneToOneField(User)
# Other fields here
company = models.ManyToManyField(Company)
# !!!! OR !!!!
company = models.ForeignKey(Company)
更新
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)
我现在已将此位添加到UserProfile类,并将AUTH_PROFILE_MODULE = 'MyApp.UserProfile'
添加到设置中。
当我执行syncdb时,收到错误消息:
>> company = models.ForeignKey(Company)
NameError: name 'Company' is not defined
答案 0 :(得分:1)
ManyToManyField
允许User
属于多个Company
。根据您的规范,ForeignKey
是合适的。