猿问

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

我目前使用单表继承策略映射类层次结构(我无法使用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)


谁能指出如何重用另一个子类已定义的列?


慕桂英546537
浏览 240回答 2
2回答

繁星点点滴滴

直接根据解决列冲突中的文档进行改编:from sqlalchemy import *from sqlalchemy.orm import *from sqlalchemy.ext.declarative import declarative_base, declared_attrBase = declarative_base()class Parent(Base):&nbsp; &nbsp; __tablename__ = 'mytable'&nbsp; &nbsp; id = Column(Integer, primary_key = True)&nbsp; &nbsp; type = Column(String(32), nullable = False)&nbsp; &nbsp; __mapper_args__ = {&nbsp; &nbsp; &nbsp; &nbsp; 'polymorphic_on' : type,&nbsp; &nbsp; &nbsp; &nbsp; 'polymorphic_identity' : 'parent'&nbsp; &nbsp; }class Child1(Parent):&nbsp; &nbsp; __mapper_args__ = { 'polymorphic_identity' : 'child1' }&nbsp; &nbsp; @declared_attr&nbsp; &nbsp; def property1(cls):&nbsp; &nbsp; &nbsp; &nbsp; return Parent.__table__.c.get('property1', Column(Integer))class Child2(Parent):&nbsp; &nbsp; __mapper_args__ = { 'polymorphic_identity' : 'child2' }&nbsp; &nbsp; @declared_attr&nbsp; &nbsp; def property1(cls):&nbsp; &nbsp; &nbsp; &nbsp; return Parent.__table__.c.get('property1', Column(Integer))class Child3(Parent):&nbsp; &nbsp; __mapper_args__ = { 'polymorphic_identity' : 'child3' }&nbsp; &nbsp; 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):&nbsp; &nbsp; if isinstance(p, (Child1, Child2)):&nbsp; &nbsp; &nbsp; &nbsp; print p.property1&nbsp; &nbsp; elif isinstance(p, Child3):&nbsp; &nbsp; &nbsp; &nbsp; print p.other_property
随时随地看视频慕课网APP

相关分类

Python
我要回答