Hi everybody
I would like to build a genealogical model called Person in which a Person has a father and a mother
Father and Mother came from the same model Person
I need some recurse model to do this like this
Class Person (models.Model)
blah, blah, blah
Father = models.ForeignKey('self',null=True,related_name='Person',on_delete=models.CASCADE)
Mother = models.ForeignKey('self',null=True,related_name='Person',on_delete=models.CASCADE)
but I got some errors when I try to makemigrations
suivi.Person.Mother: (fields.E302) Reverse accessor for 'suivi.Person.Mother' clashes with field name 'suivi.Person.Mother'.
HINT: Rename field 'suivi.Person.Mother', or add/change a related_name argument to the definition for field 'suivi.Person.Mother'.
and the same about Father
I have no problem if I use just one field like Father but one parent is missing !!
So I don’t understant how I can define a model with 2 recurse fields from the same model
Thanks for your explantions, or web references and your help
The related_name does not refer to the class to which the foreign key points. That would be the first argument of models.ForeignKey, which in this case has to be 'self' as it points to the class Person itself (which in python it cannot do in the very same class’ definition, hence the 'self').
The argument value of related_name is instead used to define what the reverse accessor on the foreign class is called. So in this case, when you have a Person object called parent, you would access the child with parent.Person. Now, not only does this clash with the same related_name being used for the other relation, in my opinion it also makes little sense when trying to model familiy relations.
There certainly is a use case for a reverse accessor of the children of a Person, but it won’t work like that, as you could only ever have one child per Person. What you may want, although this depends on your use case, is two relations for mother and father, as you have already, without a reverse accessor and then another OneToMany relation that contains the children of a Person. I’d also remove the CASCADE, as this may produce unwanted behaviour, but it also might be fully intentional.
You should also be aware that pretty much any model for familiy relations is going to run into edge cases that you can’t model, when fed real world data, but again this depends on the use case.