【问题标题】:'unique_together' refers to the non-existent field'unique_together' 指的是不存在的字段
【发布时间】:2014-11-23 07:37:28
【问题描述】:

当尝试在两个外键约束上使用 unique_together 时,我收到以下错误:

CommandError: System check identified some issues:

ERRORS:
main.AuthorTag: (models.E012) 'unique_together' refers to the non-existent field 'author'.
main.AuthorTag: (models.E012) 'unique_together' refers to the non-existent field 'tag'.

在下表中

class AuthorTag(models.Model):
    class Meta:
        unique_together = (('tag', 'author',),)
    tag = models.ForeignKey(TagIndex, on_delete=models.CASCADE),
    author = models.ForeignKey(Author, on_delete=models.CASCADE),

同样的例子似乎在这里工作:Unique foreign key pairs with Django 但是我不知道为什么会出现这个错误

编辑: 将unique_together = (('tag', 'author',),) 更改为unique_together = (('tag', 'author')) 给我同样的错误。以及将元类移动到字段声明下方。

【问题讨论】:

  • 不幸的是,移动元类没有效果

标签: django django-models django-database


【解决方案1】:

去掉结尾的逗号,使代码:

class AuthorTag(models.Model):
    class Meta:
        unique_together = ['tag', 'author']

    tag = models.ForeignKey(TagIndex, on_delete=models.CASCADE)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

让它工作。我不确定为什么。

【讨论】:

  • 我刚遇到同样的问题,这是因为尾随逗号。 unique_together = ('tag', 'author') 仍然对我有用。
  • 在我的例子中,问题是由于我不小心在外键实例化的末尾添加了一个逗号的语法错误:some_key = models.ForeignKey(Questions, on_delete=models.CASCADE),(注意最后的逗号,这个语法错误产生了同样的错误。)
  • 我的情况也是逗号!!难以置信,这不会引发错误
猜你喜欢
  • 2017-01-14
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
  • 2016-08-17
  • 1970-01-01
  • 1970-01-01
  • 2016-04-12
相关资源
最近更新 更多