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

穿精又带淫゛_ 提交于 2019-12-06 13:41:37

问题


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:


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


来源:https://stackoverflow.com/questions/33445486/how-to-make-two-foreign-keys-to-same-model-unique-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!