我有一个 django 模型如下:
class Subscription(models.Model):
Transaction = models.ManyToManyField(Transaction, blank=True, null=True)
User = models.ForeignKey(User)
...etc...
我正在尝试将 ManyToMany 字段添加到用户模型中,如下所示:
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'
如果我将 User 用引号引起来,我会得到:
sales.subscription: 'User' has a relation with model User, which has either not been installed or is abstract.
我知道用户模型已正确导入。有什么想法为什么有 2 个字段指向用户模型会导致问题吗?提前致谢...
失败的原因是因为你的字段名称与类名称(User)相同。使用小写字段名称,这是 Django 和 Python 中的标准约定。看Django 编码风格 https://docs.djangoproject.com/en/1.3/internals/contributing/#coding-style
另外,您还需要添加一个related_name
您的关系参数:
class Subscription(models.Model):
user = models.ForeignKey(User)
sub_users = models.ManyToManyField(User, blank=True, null=True, related_name="subscriptions")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)