单表继承声明的SQLAlchemy单体关系

2024-05-19 20:27:42 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我有这个模型,其中我在一个表中映射了一个“BaseNode”类和两个子类。关键是我需要其中一个子类,与另一个子类有一对多的关系。 所以在sort中,它是与另一行不同类(子类)的关系,但在同一个表中。 你觉得我怎么能用声明性语法来写呢?。

注意:由于模型中的其他关系,如果可能的话,我确实需要坚持单表继承。

class BaseNode(DBBase):
    __tablename__ = 'base_node'
    id = Column(Integer, primary_key=True)
    discriminator = Column('type', String(50))
    __mapper_args__ = {'polymorphic_on': discriminator}

class NodeTypeA(BaseNode):
    __mapper_args__ = {'polymorphic_identity': 'NodeTypeA'}
    typeB_children = relationship('NodeTypeB', backref='parent_node')


class NodeTypeB(BaseNode):
    __mapper_args__ = {'polymorphic_identity': 'NodeTypeB'}
    parent_id = Column(Integer, ForeignKey('base_node.id'))

使用此代码将引发:

sqlalchemy.exc.ArgumentError: NodeTypeA.typeB_children and back-reference NodeTypeB.parent_node are both of the same direction . Did you mean to set remote_side on the many-to-one side ?

有什么想法或建议吗?


Tags: 模型idnodebase关系argscolumn子类