我有4个django模型:
class KeyOne(models.Model):
name = models.CharField(unique=True)
class KeyTwo(models.Model):
name = models.CharField(unique=True)
class KeyThree(models.Model):
name = models.CharField(unique=True)
class KeyList(models.Model):
key_one = models.ForeignKey(KeyOne)
key_two = models.ForeignKey(KeyTwo)
key_three = models.ForeignKey(KeyThree)
list = models.CharField()
基本上,KeyList
是与KeyOne
,KeyTwo
和KeyThree
的不同组合相关联的关键字列表。如何确保在Django Admin中只能输入唯一的组合?
答案 0 :(得分:2)
您必须在KeyList中设置Meta类:
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"),)
答案 1 :(得分:1)
Django> 2.2
Django文档说:
改为使用UniqueConstraint与Constraints选项。 UniqueConstraint提供的功能比unique_together还要多。将来可能不推荐使用unique_together。
所以在您的情况下:
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")
]