簡體   English   中英

Django無向唯一在一起

[英]Django undirected unique-together

我想對集合中所有成員之間的成對關系建模。

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')

當我添加一對AB時,它成功阻止我再次添加AB,但是並不能阻止我添加BA。

我嘗試跟隨,但無濟於事。

unique_together = (('ingredient_a', 'ingredient_b'), ('ingredient_b', 'ingredient_a'))

編輯:我需要為每對項目都唯一的relationship_value

如果您按照定義的方式定義模型,則不僅是外鍵,還稱為ManyToMany Relation。

在Django文檔中,明確定義了對於ManyToMany Relation不能包括唯一的共同約束。

從文檔中

ManyToManyField不能包含在unique_together中。 (尚不清楚這意味着什么!)如果您需要驗證與ManyToManyField相關的唯一性,請嘗試使用信號或顯式直通模型。

編輯

經過大量搜索和反復試驗后,我終於找到了針對您的方案的解決方案。 是的,正如您所說,目前的架構並不像我們所有人認為的那么瑣碎。 在這種情況下,多對多關系不是我們需要轉發的討論。 解決方案是(或我認為解決方案是) 模型清潔方法

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')})

有關模型清理方法的更多詳細信息,請參閱此處文檔...

我重寫了對象的save方法,每次都保存2對。 如果用戶要添加一對AB,則會自動添加具有相同參數的記錄BA。

注意: 此解決方案會影響查詢速度。 對於我的項目,這不是問題,但是需要考慮。

 def save(self, *args, **kwargs): if not Match.objects.filter(foo_a=self.foo_a, foo_b=self.foo_b).exists(): super(Match, self).save(*args, **kwargs) if not Match.objects.filter(foo_a=self.foo_b, foo_b=self.foo_a).exists(): Match.objects.create(foo_a=self.foo_b, foo_b=self.foo_a, bar=self.bar) 

編輯:當然,更新和刪除方法也需要被覆蓋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM