Django反向查找具体示例

时间:2012-12-12 23:55:21

标签: django django-models reverse-lookup

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

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'

我似乎无法得到它,其他任何人都能看到正在发生的事情或任何建议吗?感谢。

2 个答案:

答案 0 :(得分:1)

知道了,related_name='relative'正在创建反向查找,而不是relative而不是relative_set

relationship = Relationship.objects.get(id=1)
personA = relationship.person
personB = relationship.relative.all().get()

答案 1 :(得分:1)

我认为这种情况通过Relationship更适合recursive relationship人本身。