如何将UserProfile绑定到User和另一个模型?

时间:2012-06-22 16:48:46

标签: django

我创建了公司模型和个人资料模型。

每个用户都属于一个公司,公司可以属于许多用户。

这两个中哪一个是正确的建模方式?

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

1 个答案:

答案 0 :(得分:1)

ManyToManyField允许User属于多个Company。根据您的规范,ForeignKey是合适的。