0

I am working with the following database table design. The relationship is one-to-many, parent to child. So one parent (mother or father) has multiple children. I'm having issues mapping these tables because the child's column parent_id is a Foreign Key to both of the parent tables.

class Mother(Base):
    id = Column(Integer, primary_key=True)
    child_id = Column(Integer, ForeignKey('child.unique_id'))


class Father(Base):
    id = Column(Integer, primary_key=True)
    child_id = Column(Integer, ForeignKey('child.unique_id'))


Class Children(Base):
    id = Column(Integer, primary_key=True)
    unique_id = Column(Integer, ForeignKey('mother.child_id')

I have tried defining a relationship with backref in the parent tables to avoid explicitely defining Foreign Keys in the child tables:

class Mother(Base):    
    id = Column(Integer, primary_key=True)
    child_id = Column(Integer, ForeignKey('child.unique_id'))
    children = relationship('Child', backref='mother')


class Father(Base):
    id = Column(Integer, primary_key=True)
    child_id = Column(Integer, ForeignKey('child.unique_id'))
    children = relationship('Child', backref='father')


Class Children(Base):
    id = Column(Integer, primary_key=True)
    unique_id = Column(Integer)

But this yields a one-to-one relationship.

1 Answer 1

0

I think that foreign keys should bo on Child table, it would be better and more realistic model:

class Mother(Base):    
    id = Column(Integer, primary_key=True)
    children = relationship('Child', backref='mother')

class Father(Base):
    id = Column(Integer, primary_key=True)
    children = relationship('Child', backref='father')

class Child(Base):
    id = Column(Integer, primary_key=True)
    father_id = Column(Integer, ForeignKey('father.id'))
    mother_id = Column(Integer, ForeignKey('mother.id'))

In above model, each child has at most one mother and one father, while a mother/father can have many children.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.