1
class Base(DBO):
    __tablename__ = 't'
    __mapper_args__ = {'polymorphic_on': 'typ'}
    id = Column(Integer, primary_key=True)
    typ = Column(String)

class ChildA(Base):
    __mapper_args__ = {'polymorphic_identity':'a'}

class ChildB(Base):
    __mapper_args__ = {'polymorphic_identity':'b'}

S.query(Base).all()

这对表中的所有 typ='a' 和 typ='b' 都很有效,但是假设多态加载程序遇到 'c'?

我想要的是为任何未知的 PMI 取回 Base() 的实例,我目前收到错误消息:No such polymorphic identity 'c' is defined

编辑:使用 SA 0.8.0b2

4

1 回答 1

4
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')]
于 2013-03-12T02:12:04.963 回答