【问题标题】:Django model with Foreign Key and ManyToMany relations to same model具有外键和多对多关系的 Django 模型与同一模型
【发布时间】:2011-11-15 11:53:23
【问题描述】:

我有一个 django 模型如下:

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

我正在尝试向 User 模型添加一个 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'

如果我用引号括住用户,我会得到:

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

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

【问题讨论】:

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


    【解决方案1】:

    之所以失败,是因为你的字段名与类名(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")
    

    【讨论】:

      猜你喜欢
      • 2012-07-22
      • 2012-07-28
      • 2014-05-16
      • 1970-01-01
      • 2023-01-26
      • 2012-08-27
      • 1970-01-01
      • 2014-05-20
      • 2012-03-16
      相关资源
      最近更新 更多