2012-06-22 34 views
1

我已創建公司模型和配置文件模型。如何將UserProfile綁定到用戶和另一個模型?

每個用戶屬於一個公司,一個公司可以屬於多個用戶。

這兩者中的哪一個是建模的正確方法?

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) 

現在用戶配置的定義如下:

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

一個ManyToManyField將允許User屬於多個Company秒。根據您的規格,ForeignKey將是適當的。

+0

對不起,我遇到了後續問題,你會知道爲什麼它不同步? (查看更新的問題)謝謝 – Houman

+0

Err ...你曾經輸入過這個名字嗎? –

+0

在我的models.py下?我有以下的進口:從django.db進口車型 進口UUID 從django.contrib.auth.models導入用戶 從django.db.models.signals導入post_save – Houman

相關問題