如何使用关系在 SQLAlchemy 中使用外键自动填充 table?

How to autofill table with foreign keys in SQLAlchemy using relationships?

使用 SQLAlchemy 我有三个模型:Parent1Parent2Child,其中Parent1Parent2有one-to-one关系,两者与[=有相同关系30=]Child。他们是:

from extensions import db_session

class Parent1(Base):
    __tablename__ = 'parent1'
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    
    parent2 = relationship("Parent2", backref="parent1", uselist=False)
    child = relationship("Child", backref="parent1", uselist=False)



class Parent2(Base):
    __tablename__ = 'parent2'
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    parent1_id = Column(Integer, ForeignKey('parent1.id'))

    child = relationship("Child", backref="parent2", uselist=False)

class Child(Base):
    id = Column(Integer, primary_key=True)
    parent1_id = Column(Integer, ForeignKey('parent1.id'))
    parent2_id = Column(Integer, ForeignKey('parent2.id'))

我想要实现的是用它的 parents' 外键填充 Child table。 所以,当我执行这个:

parent1 = Parent1(name="Adil")
parent1.parent2 = Parent2(name="Aisha")
parent1.child = Child()
db_session.add(parent1)
db_session.commit()

到parents table它根据需要插入数据,但是到Child table它插入数据像这样:

Child

id  parent1_id  parent2_id
 1           1        NULL

如何正确设置关系,以便在任何插入到 Parent1->Parent2 tables 时它也将其 ID 作为外键插入 Child table?

我要实现的是:

Child

id  parent1_id  parent2_id
 1           1           1

我想出了这个 solution。我删除了声明的模型 Child 并在两个模型之间创建了关联 table 并添加了辅助参数填充关联 table name:

Base = declarative_base()

child = Table('child', Base.metadata,
               Column('parent1_id', Integer, ForeignKey('parent1.id')),
               Column('parent2_id', Integer, ForeignKey('parent2.id')))


class Parent1(Base):
    __tablename__ = 'parent1'
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)

    parent2 = relationship("Parent2", secondary='child', uselist=False)


class Parent2(Base):
    __tablename__ = 'parent2'
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    parent1_id = Column(Integer, ForeignKey('parent1.id'))