0

我有两个模型类,Person如下Relationship所示,为简洁起见省略了字段:

class Person(models.Model):
    first_name = models.CharField(max_length=32, null=True)
    .
    .
    .
    relationship = models.ManyToManyField('Relationship', related_name='relative')


class Relationship(models.Model):
    person = models.ForeignKey('Person', related_name='relative', null=True)

假设 A 是父亲,B 是女儿。我会按如下方式创建它们:

personA = Person()
personA.first_name = "Father"
personA.save()

personB = Person()
personB.first_name = "Daughter"
personB.save()

那么它们之间的关系:

daughterRelationship = Relationship()
daughterRelationship.person = personB
daughterRelationship.save()
personA.relationship.add(daughterRelationship)

fatherRelationship = Relationship()
fatherRelationship.person = personA
fatherRelationship.save()
personB.relationship.add(fatherRelationship)

现在,根据我的模型(可能是 related_name='relative' 导致了问题),但我似乎无法弄清楚我的反向查找名称。

我已经尝试过这些,但无济于事:

relationship = Relationship.objects.get(id=1)
personA = relationship.person
personB = relationship.relative_set.all().get() # Relationship does not have attribute 'relative_set'
personB = relationship.person_set.all().get() # Relationship does not have attribute 'person_set'
personB = relationship.relationship_set.all().get() # Relationship does not have attribute 'relationship_set'
personB = relationship.personrelationship_set.all().get() # Relationship does not have attribute 'personrelationship_set'
personB = relationship.personrealtive_set.all().get() # Relationship does not have attribute 'personrelative_set'

我似乎无法得到它,其他人可以看到发生了什么,或者有什么建议吗?谢谢。

4

2 回答 2

1

明白了,related_name='relative'正在创建反向查找relative而不是relative_set.

relationship = Relationship.objects.get(id=1)
personA = relationship.person
personB = relationship.relative.all().get()
于 2012-12-13T00:12:43.180 回答
1

我认为这种情况更适合Person 与自身的递归关系Relationshipthrough 。

于 2012-12-13T00:13:16.353 回答