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

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


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

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


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

谢谢 !

最佳答案

我建议您使用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')})

09-26 10:55