简体   繁体   English

Django独特的外键组合

[英]Django unique combination of foreign keys

I have 4 django models:我有 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()

Basically, KeyList is a list of keywords associated with different combinations of KeyOne , KeyTwo and KeyThree .基本上, KeyList是与KeyOneKeyTwoKeyThree不同组合相关联的关键字列表。 How do I make sure that, in the Django Admin, only unique combos can be entered?我如何确保在 Django Admin 中只能输入唯一的组合?

You have to set in the Meta class in the KeyList:您必须在 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"),)

Django > 2.2姜戈 > 2.2

Django Documentation says : Django 文档说

Use UniqueConstraint with the constraints option instead.改为使用具有约束选项的 UniqueConstraint。 UniqueConstraint provides more functionality than unique_together. UniqueConstraint 提供了比 unique_together 更多的功能。 unique_together may be deprecated in the future. unique_together 将来可能会被弃用。

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")
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM