python - Django 无向唯一在一起

标签 python django model unique-constraint

我想对集合中所有成员之间的成对关系进行建模。

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/

相关文章:

python - pandas 在 groupby 上设置 withcopywarning

python - 你能推荐一些 Python HTTP 客户端库吗?

django - 无效操作: Invalid literal for Decimal: u' '

gridview - Yii2:如何将查询参数添加到索引操作的searchModel而不影响gridview的过滤模型

javascript - 在数据库中创建新记录 (Sails.js)

python - 如果字符串包含重复单词,则仅保留第一个单词

c# - 用脚本语言解析 C#

python - 使用 python 的旧式字符串格式时,Django 无法处理 sql 中的 % 符号

html - django 如何使用模板创建注销链接?

PHP MVC,谁拥有 URL?