假设我有一个关系类,例如:
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')})