为了账号安全,请及时绑定邮箱和手机立即绑定

SQLAlchemy:单表继承,子级中的同一列

SQLAlchemy:单表继承,子级中的同一列

慕桂英546537 2021-03-28 14:38:23
我目前使用单表继承策略映射类层次结构(我无法使用joind)。该层次结构可能如下所示:class Parent(Base):    __tablename__ = 'mytable'    __mapper_args__ = {        'polymorphic_on' : type,        'polymorphic_identity' : 'parent'    }    id = Column(Integer, primary_key = True)    type = Column(String(32), nullable = False)class Child1(Parent):    __mapper_args__ = { 'polymorphic_identity' : 'child1' }    property1 = Column(Integer)class Child2(Parent):    __mapper_args__ = { 'polymorphic_identity' : 'child2' }    property1 = Column(Integer)class Child3(Parent):    __mapper_args__ = { 'polymorphic_identity' : 'child3' }    other_property = Column(Integer)那么问题是,我想有一property1两个Child1和Child2,但不是Child3。上面的当前代码导致错误:sqlalchemy.exc.ArgumentError: Column 'property1' on class <class'__main__.Child2'>  conflicts with existing column 'mytable.property1'我当然可以添加其他层的继承层次这Child1与Child2从派生,并包含property1列,但Child1和Child2几乎不相互关联的,但我想重用这两个类相同的数据库列。我已经尝试添加property1 = Child1.property1到,Child2但没有成功(实例值未存储在的数据库中Child2)谁能指出如何重用另一个子类已定义的列?
查看完整描述

2 回答

?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

直接根据解决列冲突中的文档进行改编:


from sqlalchemy import *

from sqlalchemy.orm import *

from sqlalchemy.ext.declarative import declarative_base, declared_attr


Base = declarative_base()


class Parent(Base):

    __tablename__ = 'mytable'


    id = Column(Integer, primary_key = True)

    type = Column(String(32), nullable = False)

    __mapper_args__ = {

        'polymorphic_on' : type,

        'polymorphic_identity' : 'parent'

    }


class Child1(Parent):

    __mapper_args__ = { 'polymorphic_identity' : 'child1' }


    @declared_attr

    def property1(cls):

        return Parent.__table__.c.get('property1', Column(Integer))


class Child2(Parent):

    __mapper_args__ = { 'polymorphic_identity' : 'child2' }


    @declared_attr

    def property1(cls):

        return Parent.__table__.c.get('property1', Column(Integer))


class Child3(Parent):

    __mapper_args__ = { 'polymorphic_identity' : 'child3' }


    other_property = Column(Integer)


e = create_engine("sqlite://", echo=True)

Base.metadata.create_all(e)


s = Session(e)

s.add_all([Child1(property1=1), Child2(property1=2), Child3(other_property=3)])

s.commit()


for p in s.query(Parent):

    if isinstance(p, (Child1, Child2)):

        print p.property1

    elif isinstance(p, Child3):

        print p.other_property


查看完整回答
反对 回复 2021-04-01
  • 2 回答
  • 0 关注
  • 239 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号