' unique_together'指不存在的字段

时间:2014-09-29 00:21:13

标签: 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'.

在下表中

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'))会给我同样的错误。以及在领域声明下面移动元类。

1 个答案:

答案 0 :(得分: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)

让它发挥作用。我不确定为什么。