2

假设我有以下模型:

class Person(models.Model):
    related_people = models.ManyToManyField('Person',
                                            blank=True,
                                            related_name='ret_related_people',
                                            through='RelationshipType')

class RelationshipType(models.Model):
    person1 = models.ForeignKey('Person', related_name='rel_back_1')
    person2 = models.ForeignKey('Person', related_name='rel_back_2')

    type = models.CharField(max_length=16)

有什么方法可以防止 aPerson与自身相关吗?

4

1 回答 1

0

未经测试:

class Person(models.Model):
    related_people = models.ManyToManyField('self',
                                        blank=True,
                                        related_name='ret_related_people',
                                        through='RelationshipType',
                                        symmetrical=False)

class RelationshipType(models.Model):
    from_person = models.ForeignKey('Person', related_name='from_people')
    to_person = models.ForeignKey('Person', related_name='to_people')
    type = models.CharField(max_length=16)

    def clean(self):
        if self.from_person == self.to_person:
            from django.core.exceptions import ValidationError
            raise ValidationError("People can't have a relationship to self")
于 2013-08-02T23:04:54.890 回答