Django self-referential foreign key with related_name doesn't work -
i followed this question create model pointing foreignkey. added related_name option. model looks 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 did following:
>>> = 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 @ 0x102503190>
i don't understand why when query m.considered_best_friend_for.all()
empty result []
. expecting [<albert>, <john>]
. however, if query m.considered_best_friend_for
relatemanager object. mistake?
note: tried same code changing foreignkey manytomany relationship , worked, in case need foreignkey relationship because person can considered best friend more 1 person (or zero), can consider 1 (or zero) person his/her best friend.
thank you!
mistake found! using custom manager (needed part of code) filtering out results. sorry that! :)
Comments
Post a Comment