[Solved]-Django multiple foreign key, Same related name

12👍

The related_names can not be the same, since this would introduce confusion: an object that is related through the mother is not (exactly) the same as an object related through the father.

You can alter your modeling (for example by introducing a ManyToManyField with the Parent, and for example add extra data in the relation about the sex of the parent). But a disavantage of this approach is that now, you no longer set the cardinality of the relation to 2: it means a Child can (by desing) have zero parents, one parent, two parents, three parents, or more. Furthermore it could be possible that a child has two mothers, or two fathers, or two mothers and three fathers. So it can result in a lot of extra logic to prevent certain cases. Note that in some countries that is possible: in some countries extra people can be listed as “parents”, and they have the same legal rights and duties as a parent.

You can however define such property to obtain the children, by making a query to fetch all Child objects where the mother, or the father is self:

from django.db.models import Q

class Parent(Model):
    name = models.CharField(max_length=100)

    @property
    def children(self):
         return Child.objects.filter(Q(mother=self) | Q(father=self))

You could for example name the related names 'father_of' and 'mother_of' such that you can query some_parent.mother_of to obtain children where the some_parent is the mother_of. This could be useful if you for example would want to list a table with mothers and their children, or if you would make an application where it is possible that Parents change gender.

If you however want to have strict Fathers and Mothers, then it might be beneficial to define two separate models. The advantage is that you can both name the related_names 'children' then, and furthermore by design you check that the father of a Child is a male (and similar for a mother being female).

Leave a comment