具有外键和与同一模型的多对多关系的 Django 模型

发布于 2024-12-04 07:52:09 字数 841 浏览 0 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

提笔书几行 2024-12-11 07:52:09

失败的原因是因为你的字段名称与类名称(User)相同。使用小写字段名称,这是 Django 和 Python 中的标准约定。请参阅 Django 编码风格

此外,您还需要添加 < code> related_name 与您的关系的参数:

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

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_nameparameter to your relationship:

class Subscription(models.Model):
    user = models.ForeignKey(User)
    sub_users = models.ManyToManyField(User, blank=True, null=True, related_name="subscriptions")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文