from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Root(Base):
__tablename__ = 't'
id = Column(Integer, primary_key=True)
typ = Column(String)
def __repr__(self):
return "%s(typ=%r)" % (self.__class__.__name__, self.typ)
__mapper_args__ = {
'polymorphic_on': case([(typ.in_(['a', 'b']), typ)], else_='t'),
'polymorphic_identity': 't'
}
class ChildA(Root):
__mapper_args__ = {'polymorphic_identity': 'a'}
class ChildB(Root):
__mapper_args__ = {'polymorphic_identity': 'b'}
e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)
e.execute(
Root.__table__.insert(), [
{'typ': 'a'},
{'typ': 'a'},
{'typ': 'b'},
{'typ': 'a'},
{'typ': 'c'},
{'typ': 't'},
]
)
print Session(e).query(Root).all()
输出,数据插入后:
SELECT t.id AS t_id, t.typ AS t_typ,
CASE WHEN (t.typ IN (?, ?)) THEN t.typ ELSE ? END AS _sa_polymorphic_on
FROM t
('a', 'b', 't')
[ChildA(typ=u'a'), ChildA(typ=u'a'), ChildB(typ=u'b'), ChildA(typ=u'a'), Root(typ=u'c'), Root(typ=u't')]