Guest User

Untitled

a guest
Jun 17th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1.  
  2.  
  3.  
  4. from sqlalchemy import *
  5. from sqlalchemy import engine_from_config
  6. from sqlalchemy.ext.declarative import declarative_base
  7. from sqlalchemy.orm import sessionmaker, scoped_session
  8.  
  9.  
  10. Base = declarative_base()
  11. Session = scoped_session(sessionmaker())
  12.  
  13.  
  14. class A(Base):
  15.     __tablename__ = 'a'
  16.     id = Column(Integer, primary_key=True)
  17.     type = Column(String)
  18.    
  19.     __mapper_args__ = {'polymorphic_on': type}
  20.    
  21.    
  22. class B(A):
  23.     __tablename__ = 'b'
  24.     id = Column(Integer, primary_key=True)
  25.     a_id = Column(Integer, ForeignKey('a.id'))
  26.     subtype = Column(String)
  27.     __mapper_args__ = {'polymorphic_identity': 'B',
  28.                     'polymorphic_on': subtype}
  29.  
  30.        
  31.    
  32. class Bx(A):
  33.     __mapper_args__ = {'polymorphic_identity': 'Bx'}
  34.    
  35.  
  36. class By(A):
  37.     __mapper_args__ = {'polymorphic_identity': 'By'}
  38.    
  39. engine = engine_from_config({'sqlalchemy.url' : 'sqlite:///:memory:'})
  40. Session.configure(bind=engine)
  41. Base.metadata.create_all(engine)
  42.  
  43. Session.add(B())
  44. Session.add(Bx())
  45. Session.add(By())
  46. print Session.query(A).all()
  47.  
  48. ## Results:
  49.  
  50. [<__main__.A object at 0x27b5b50>, <__main__.Bx object at 0x27b5d10>, <__main__.By object at 0x27b5c10>]
Add Comment
Please, Sign In to add comment