Seb*_*ann 4 python orm sqlalchemy single-table-inheritance
我目前使用单表继承策略映射类层次结构(我不可能使用join).此层次结构可能如下所示:
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)
Run Code Online (Sandbox Code Playgroud)
那么问题是我希望property1两者都有Child1,Child2但不是Child3.上面的当前代码导致错误:
sqlalchemy.exc.ArgumentError: Column 'property1' on class <class
'__main__.Child2'> conflicts with existing column 'mytable.property1'
Run Code Online (Sandbox Code Playgroud)
我当然可以在继承层次结构中添加另一个层,Child1并Child2从派生和包含property1列,但是Child1和Child2几乎不相互关联的,但我想重用这两个类相同的数据库列.
我已经尝试添加property1 = Child1.property1到Child2但didnt工作(实例值不存储在数据库中,Child2)
任何人都可以指出如何重用已经由另一个子类定义的列?
zzz*_*eek 12
直接从解决列冲突中的文档进行调整:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1978 次 |
| 最近记录: |