SQLAlchemy与声明属性的邻接列表关系

时间:2016-03-23 19:08:25

标签: python sqlalchemy

我有一个由不同类型的孩子继承的顶级模型声明

class HasId(object):

    @declared_attr
    def id(cls):
        return Column('id', Integer, Sequence('test_id_seq'), primary_key=True)
    ...
    @declared_attr
        def triggered_by_id(cls):
            return Column(Integer, ForeignKey('tests.id'), nullable=True)

    @declared_attr
        def triggered(cls):
            return relationship('TestParent',
                                foreign_keys='TestParent.triggered_by_id',
                                lazy='joined',
                                cascade='save-update, merge, delete, delete-orphan',
                                backref=backref('triggered_by', remote_side=[id])
                                )


class TestParent(HasId, Model):
    __tablename__ = 'tests'

    discriminator = Column(String(50))

    __mapper_args__ = {'polymorphic_on': discriminator}


class FooTest(TestParent):
    __tablename__ = 'footests'
    __mapper_args__ = {'polymorphic_identity': 'footests'}
    id = Column(Integer, ForeignKey('tests.id'), primary_key=True)

    bar = Column(Boolean)
    ...

当IO尝试构建此数据库时,由于我在remote_side关系中定义backref的{​​{1}}而导致错误。

完整错误是

triggered_by

1 个答案:

答案 0 :(得分:4)

解决方案是从

更改backref定义
backref('triggered', remote_side=[id])

backref('triggered', remote_side='TestParent.id')