How to make two foreign keys to same model unique together?

时间:2015-10-30 21:55:29

标签: python django foreign-keys unique foreign-key-relationship

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 !

1 个答案:

答案 0 :(得分:1)

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

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