6

When trying to use unique_together on two foreign key constraints, I get the following error:

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'.

On the following table

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),

The same example seems to work here: Unique foreign key pairs with Django But I can't figure out why I get this error

EDIT: changing unique_together = (('tag', 'author',),) to unique_together = (('tag', 'author')) give me the same error. as well as moving the meta class below the field declarations.

Community
  • 1
  • 1
evrom
  • 93
  • 1
  • 5

1 Answers1

2

Removing the trailing commas, making the code to:

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)

Made it work. I am unsure why.

evrom
  • 93
  • 1
  • 5
  • I just faced the same problem, It is because of the trailing commas. unique_together = ('tag', 'author') still works for me. – Karthik RP May 14 '18 at 06:15
  • 2
    In my case, the problem was due to a syntax error where I accidentally added a comma at the end of the foreign key instantiation: `some_key = models.ForeignKey(Questions, on_delete=models.CASCADE),` (notice the comma at the end, this syntax mistake produced the same error.) – precise Sep 13 '19 at 18:31
  • My case was the comma too!! Incredible that this does not throw an error – Marcos Pereira Dec 08 '21 at 18:18