Question

I have two model classes, Person and Relationship as follows with fields omitted for brevity:

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)

Let's say Person A is a father and Person B is a daughter. I would have create them as follows:

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

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

Then the relationships between them:

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

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

Now, based on my models (maybe related_name='relative' is causing the issue), but I can't seem to figure out my reverse lookup name.

I've tried these, but to no avail:

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'

I can't seem to get it, can anybody else see what's going on, or any suggestions? Thanks.

Was it helpful?

Solution

I think this situation is better suited to a recursive relationship of Person to itself through Relationship.

OTHER TIPS

Got it, the related_name='relative' was creating the reverse lookup as relative instead of relative_set.

relationship = Relationship.objects.get(id=1)
personA = relationship.person
personB = relationship.relative.all().get()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top