[Django]-Django unique combination of foreign keys

5👍

You have to set in the Meta class in the KeyList:

class KeyList(models.Model):
    key_one = models.ForeignKey(KeyOne)
    key_two = models.ForeignKey(KeyTwo)
    key_three = models.ForeignKey(KeyThree)
    list = models.CharField()
    class Meta:
        unique_together = (("key_one", "key_two", "key_three"),)
👤bcap

11👍

Django > 2.2

Django Documentation says:

Use UniqueConstraint with the constraints option instead.
UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future.

So in your case:

class KeyList(models.Model):
    key_one = models.ForeignKey(KeyOne)
    key_two = models.ForeignKey(KeyTwo)
    key_three = models.ForeignKey(KeyThree)
    list = models.CharField()
    class Meta:
        constraints = [
            models.UniqueConstraint(fields=["key_one", "key_two", "key_three"], name="all_keys_unique_together")
]

Leave a comment