Django中是否有内置解决方案,仅当两个对象的外键不同时,才让两个对象的字段具有相同的值。
例如,只有两个孩子的母亲不同,两个孩子才能使用相同的名字:
class Child(models.Model):
name = models.CharField(unique=True, max_length=25)
mother = models.ForeignKey(Mother, on_delete=models.CASCADE, blank=False)
class Mother(models.Model):
name = models.CharField(unique=True, max_length=25)
您可以使模型上的字段一起唯一。这意味着各个字段可以相同,只要唯一共同约束中的至少一个字段不同即可。
class Mother(models.Model):
name = models.CharField(unique=True, max_length=25)
class Child(models.Model):
name = models.CharField(unique=True, max_length=25)
mother = models.ForeignKey(Mother, on_delete=models.CASCADE, blank=False)
class Meta:
unique_together = ('name', 'mother')
但是,您不能对相关模型上的字段实施唯一的唯一约束。例如,unique_together = ('child_field', 'mother__mother_field')
将不允许。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句