本文介绍了如何使相同模型的两个外键一起唯一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个关系类,例如:

  class Friendship(models.Model):
person1 = models.ForeignKey(Person,related_name ='person1')
person2 = models.ForeignKey(Person,related_name ='person2')

所以我想使该对象对于一对 Person s是唯一的。如果我只是简单地做 unique_together =(( person1, person2),),那么我可以得到两个 Friendship

  FS1.person1 = A,FS1.person2 = B 
FS2.person1 = B,FS2的对象.person2 = A

想要这个。我想要两个人之间独特的友谊对象。那么,如何确保任何一对 Person s最多有一个 Friendship 对象?

谢谢!

解决方案

我建议您使用model.clean方法:

  class Friendship(models.Model):
person1 = models.ForeignKey(Person,related_name ='person1')
person2 =模型。ForeignKey(Person,related_name ='person2')

def clean(self):
direct = FriendShip.objects.filter(person1 = self.person1, person2 = self.person2)
反向= FriendShip.objects.filter(person1 = self.person2,person2 = self.person1)

如果是direct.exists()或reverse.exists() :
提高ValidationError({'key':'Message')})


Let's say I have a relationship class such as:

class Friendship(models.Model):
    person1 = models.ForeignKey(Person, related_name='person1')
    person2 = models.ForeignKey(Person, related_name='person2')

so I want to make this object unique for a pair of Persons. If I simply do unique_together = (("person1", "person2"),) then I can end up with two Friendship objects where

FS1.person1 = A, FS1.person2 = B
FS2.person1 = B, FS2.person2 = A

I do not want this. I want a unique friendship object between two people. So how can I ensure that there is -at most- one Friendship object for any pair of Persons?

Thanks !

解决方案

I suggest you to use model.clean method:

class Friendship(models.Model):
    person1 = models.ForeignKey(Person, related_name='person1')
    person2 = models.ForeignKey(Person, related_name='person2')

    def clean(self):
        direct = FriendShip.objects.filter(person1 = self.person1, person2 = self.person2)
        reverse = FriendShip.objects.filter(person1 = self.person2, person2 = self.person1)

        if direct.exists() or reverse.exists():
            raise ValidationError({'key':'Message')})

这篇关于如何使相同模型的两个外键一起唯一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:26