具有外键和与同一模型的多对多关系的 Django 模型
我有一个 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'
如果我将 User 放在引号中,我会得到:
sales.subscription: 'User' has a relation with model User, which has either not been installed or is abstract.
我知道 User 模型是正确导入。有什么想法为什么有 2 个字段指向用户模型会导致问题吗?提前致谢...
I have a django model as follows:
class Subscription(models.Model):
Transaction = models.ManyToManyField(Transaction, blank=True, null=True)
User = models.ForeignKey(User)
...etc...
I am trying to add a ManyToMany field to the User model as follows:
SubUsers = models.ManyToManyField(User, blank=True, null=True)
but I get this error when I run 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'
If I encase User in quotes, I get instead:
sales.subscription: 'User' has a relation with model User, which has either not been installed or is abstract.
I know the User model is imported correctly. Any ideas why having 2 fields pointing to the User model causes problems? Thanks in advance...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
失败的原因是因为你的字段名称与类名称(User)相同。使用小写字段名称,这是 Django 和 Python 中的标准约定。请参阅 Django 编码风格
此外,您还需要添加 < code> related_name 与您的关系的参数:
The reason why it fails is because the name of your field is the same as the class name (User). Use lowercase field names, it the standard convention in Django and Python. See Django Coding style
Also, you need to add a
related_name
parameter to your relationship: