'unique_together' 指的是不存在的字段

evr*_*rom 5 django django-models django-database

尝试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'.
Run Code Online (Sandbox Code Playgroud)

在下表中

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),
Run Code Online (Sandbox Code Playgroud)

同样的例子似乎在这里工作:Unique外键对与 Django 但我不明白为什么我会收到这个错误

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

evr*_*rom 2

删除结尾的逗号,使代码:

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)
Run Code Online (Sandbox Code Playgroud)

成功了。我不确定为什么。

  • 就我而言,问题是由于语法错误造成的,我不小心在外键实例化的末尾添加了一个逗号:`some_key = models.ForeignKey(Questions, on_delete=models.CASCADE),`(请注意最后,这个语法错误产生了同样的错误。) (2认同)