Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from sqlalchemy import *
- from sqlalchemy import engine_from_config
- from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy.orm import sessionmaker, scoped_session
- Base = declarative_base()
- Session = scoped_session(sessionmaker())
- class A(Base):
- __tablename__ = 'a'
- id = Column(Integer, primary_key=True)
- type = Column(String)
- __mapper_args__ = {'polymorphic_on': type}
- class B(A):
- __tablename__ = 'b'
- id = Column(Integer, primary_key=True)
- a_id = Column(Integer, ForeignKey('a.id'))
- subtype = Column(String)
- __mapper_args__ = {'polymorphic_identity': 'B',
- 'polymorphic_on': subtype}
- class Bx(A):
- __mapper_args__ = {'polymorphic_identity': 'Bx'}
- class By(A):
- __mapper_args__ = {'polymorphic_identity': 'By'}
- engine = engine_from_config({'sqlalchemy.url' : 'sqlite:///:memory:'})
- Session.configure(bind=engine)
- Base.metadata.create_all(engine)
- Session.add(B())
- Session.add(Bx())
- Session.add(By())
- print Session.query(A).all()
- ## Results:
- [<__main__.A object at 0x27b5b50>, <__main__.Bx object at 0x27b5d10>, <__main__.By object at 0x27b5c10>]
Add Comment
Please, Sign In to add comment