简体   繁体   English

Django 强制外键对的唯一组合

[英]Django Enforce unique combination of pair of foreign keys

So let's say I have the following Django models defined:因此,假设我定义了以下 Django 模型:

class Model(models.Model):
    model_id = models.IntegerField(default=0, unique=true)
    content = models.TextField()

class ModelRelation(models.Model):
    relation_id = models.IntegerField(default=0, unique=true)
    model_id1 = models.ForeignKey(Model, on_delete=models.CASCADE)
    model_id2 = models.ForeignKey(Model, on_delete=models.CASCADE)

With a regular UniqueConstraint in the constraints option of the Meta class,在 Meta class 的约束选项中使用常规 UniqueConstraint,
a foreign key pair of model_id1 = 1 and model_id2 = 2 is allowed to coexist with允许model_id1 = 1和model_id2 = 2的外键对与
a foreign key pair of model_id1 = 2 and model_id2 = 1. model_id1 = 2 和 model_id2 = 1 的外键对。

How do I implement a behaviour like in the first answer to Postgresql enforce unique two-way combination of columns in Django?如何实现类似于 Postgresql 的第一个答案中的行为,强制在Django 中强制使用唯一的双向组合 How do you even make an unique index in Django?您甚至如何在 Django 中创建唯一索引?

You could use a ManyToMany Field which is automatically symmetrical: ManyToManyField Django Docs您可以使用自动对称的多对多字段: ManyToManyField Django Docs

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

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