2011-09-12 103 views
4

Django的模型我有一個Django模型如下:與外鍵和多對多關係,同型號

class Subscription(models.Model): 
    Transaction = models.ManyToManyField(Transaction, blank=True, null=True) 
    User = models.ForeignKey(User) 
    ...etc... 

我想一個多對多字段添加到用戶模型如下:

SubUsers = models.ManyToManyField(User, blank=True, null=True) 

但是當我運行執行syncdb我得到這個錯誤:

AssertionError: ManyToManyField(<django.db.models.fields.related.ForeignKey object at 0x19ddfd0>) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string 'self' 

如果我用引號包圍用戶,我得到相反:

sales.subscription: 'User' has a relation with model User, which has either not been installed or is abstract. 

我知道用戶模型導入正確。任何想法爲什麼有2個字段指向User模型會導致問題?在此先感謝...

回答

6

它失敗的原因是因爲您的字段名稱與類名稱(用戶)相同。使用小寫字段名稱,它是Django和Python中的標準約定。見Django Coding style

此外,您還需要一個related_name參數添加到您的關係:

class Subscription(models.Model): 
    user = models.ForeignKey(User) 
    sub_users = models.ManyToManyField(User, blank=True, null=True, related_name="subscriptions")