Django模型与Foreign Key和ManyToMany关系相同的模型

时间:2011-09-12 16:18:22

标签: django django-models foreign-keys many-to-many

我有一个django模型如下:

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

我正在尝试将ManyToMany字段添加到User模型,如下所示:

    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.

我知道用户模型已正确导入。有两个字段指向User模型的任何想法会导致问题吗?提前谢谢......

1 个答案:

答案 0 :(得分:8)

失败的原因是因为您的字段名称与类名(User)相同。使用小写字段名称,它是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")