I would like to create a model(1) with multiple foreign keys to the same other model(2).
I want these foreign keys to have the same related_name because each foreign key will point to difference instances of model(2), because I need one reversed relation for all foreign keys.
Maybe an example will be more explicit :
class Parent(Model):
name = models.CharField(max_length=100)
class Child(Model):
name = models.CharField(max_length=100)
father = models.ForeignKey(Parent, related_name='children')
mother = models.ForeignKey(Parent, related_name='children')
How can I do that ?
I already know an ugly way to do so :
class Parent(Model):
name = models.CharField(max_length=100)
@property
def children(self):
# Pick the existing one in fields 'children_1' or 'children_2'
class Child(Model):
name = models.CharField(max_length=100)
father = models.ForeignKey(Parent, related_name='children_1')
mother = models.ForeignKey(Parent, related_name='children_2')
motherandfatherwithparentsas aManyToManyFieldand add atypefield inParentmodel with choices asMorF, corresponding toMotherandFather. Then, you can have therelated_nameofparentsaschildren.