2013-03-11 2 views
0
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() 

이 테이블의 모든 일반 = 'A'와 일반 = 'B'에 대한 잘 작동하지만, 다형성 로더는 'C'를 만날 생각? No such polymorphic identity 'c' is definedSQLAlchemy의 선언적 STI 다형성 로더는

편집 : SA 0.8.0b2을 사용

답변

3
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() 

출력 내가 원하는 무엇

내가 현재 오류, 알 수없는 PMI를위한 자료()의 인스턴스를 다시 얻을 수 있습니다 , 데이터 삽입 후 :

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')] 
+0

사례() 매퍼에서 매우 좋습니다. 감사합니다 마이크! –