[Answer]-ModelForm instance with ForeignKey – unexpected behaviour

1πŸ‘

βœ…

In the following line:

logger.debug("father %s" % instance.father.all())

you call the related name father and you naturally get all children of this person.

Change the related names to something else, maybe fathers_children and mothers_children, so you don’t get confused.

If you want to get the father of a person, e.g. the current instance of the class Person, you should try the following line:

logger.debug("father %s" % instance.father)

which will return an object.

You can also do:

logger.debug("father %s" % instance.father_id)

to get the id of the father.

Nicer is to format the strings like this:

logger.debug('father {0}'.format(instance.father))

A child can have only one father and one mother, but a father (or mother) can have many children. So calling something like instance.father.all() doesn’t make a lot of sense. That would be like getting all fathers of the child, where it is only one.

πŸ‘€cezar

Leave a comment