我想对集合中所有成员之间的成对关系进行建模。
class Match(models.Model):
foo_a = models.ForeignKey(Foo, related_name='foo_a')
foo_b = models.ForeignKey(Foo, related_name='foo_b')
relation_value = models.IntegerField(default=0)
class Meta:
unique_together = ('ingredient_a', 'ingredient_b')
当我添加一对 A-B 时,它成功阻止我再次添加 A-B,但不会阻止我添加 B-A。
我尝试过关注,但没有成功。
unique_together = (('ingredient_a', 'ingredient_b'), ('ingredient_b', 'ingredient_a'))
编辑: 我需要每对项目的关系值都是唯一的
最佳答案
如果您定义一个像您所定义的模型,它不仅仅是一个外键,它称为多对多关系。
在 django 文档中,明确定义多对多关系不能包含唯一的共同约束。
来自文档,
A ManyToManyField cannot be included in unique_together. (It’s not clear what that would even mean!) If you need to validate uniqueness related to a ManyToManyField, try using a signal or an explicit through model.
编辑
经过大量搜索和一些试验和错误,最后我想我找到了适合您的场景的解决方案。是的,正如您所说,当前的模式并不像我们想象的那么微不足道。在这种背景下,多对多关系不是我们需要讨论的。解决方案是,(或者我认为的解决方案是)模型清理方法:
class Match(models.Model):
foo_a = models.ForeignKey(Foo, related_name='foo_a')
foo_b = models.ForeignKey(Foo, related_name='foo_b')
def clean(self):
a_to_b = Foo.objects.filter(foo_a = self.foo_a, foo_b = self.foo_b)
b_to_a = Foo.objects.filter(foo_a = self.foo_b, foo_b = self.foo_a)
if a_to_b.exists() or b_to_a.exists():
raise ValidationError({'Exception':'Error_Message')})
有关模型清理方法的更多详细信息,请参阅 docs here...
关于python - Django 无向唯一在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44117516/