ferrangb
ferrangb

Reputation: 2050

Django self-referential foreign key with related_name doesn't work

I followed this question to create a model pointing to itself with a ForeignKey. I just added the related_name option. The model looks like this:

class Person(models.Model):
    name = models.CharField(max_length=100)
    best_friend = models.ForeignKey('self', blank=True, null=True, 
                                    related_name='considered_best_friend_for')

def __unicode__(self):
    return self.name 

Then I did the following:

>>> a = Person.objects.create(name='Albert')
>>> a.save()
>>> j = Person.objects.create(name='John')
>>> j.save()
>>> m = Person.objects.create(name='Mark')
>>> m.save()
>>> a.best_friend = m
>>> a.save()
>>> j.best_friend = m
>>> j.save()
>>> m.considered_best_friend_for.all()
[]
>>> m.considered_best_friend_for
<django.db.models.fields.related.RelatedManager object at 0x102503190>

I don't understand why when I query m.considered_best_friend_for.all() I get an empty result []. I was expecting to get [<Albert>, <John>]. However, if I query m.considered_best_friend_for I get the RelateManager object. Where is the mistake?

Note: I tried the same code changing the ForeignKey for a ManyToMany relationship and it worked, but in this case I need a ForeignKey relationship because a person can be considered best friend for more than one person (or zero), but can only consider one (or zero) person his/her best friend.

Thank you!

Upvotes: 1

Views: 2031

Answers (1)

ferrangb
ferrangb

Reputation: 2050

Mistake found! I was using a custom manager (needed for another part of the code) that was filtering out the results. Sorry about that! :)

Upvotes: 2

Related Questions