Skip to content

Instantly share code, notes, and snippets.

@skyler
Last active August 29, 2015 13:56
Show Gist options
  • Save skyler/8938971 to your computer and use it in GitHub Desktop.
Save skyler/8938971 to your computer and use it in GitHub Desktop.
from sqlalchemy import Column, Integer, Enum
from sqlalchemy.dialects.postgresql import TEXT
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base
info = 'postgresql+psycopg2://panel_app@localhost:5432/panel_db'
engine = create_engine(info)
metadata = MetaData()
session = scoped_session(sessionmaker(bind=engine))
Base = declarative_base(metadata=metadata)
class Wave(Base):
"""Represent a Wave."""
__tablename__ = 'waves'
wave_id = Column(Integer, primary_key=True)
wave_name = Column(TEXT)
type = Column(Enum('emailed', 'triggered', 'anonymous', name='wave_type'), nullable=False)
__mapper_args = {
'polymorphic_on': type,
}
class AnonymousWave(Wave):
__mapper_args__ = {
'polymorphic_identity': 'anonymous'
}
class EmailedWave(Wave):
"""Represents a wave that is emailed out."""
__mapper_args__ = {
'polymorphic_identity': 'emailed',
}
@skyler
Copy link
Author

skyler commented Feb 11, 2014

Rows in the database are

select wave_id, wave_name, type from waves;
 wave_id |            wave_name             |  type
---------+----------------------------------+---------
       1 | Wave 1                           | emailed
      10 | MM 1 - client approval test      | emailed
       2 | Wave 1                           | emailed
       3 | Wave 1                           | emailed
       4 | Wave 1                           | emailed
       5 | Wave 1                           | emailed
       6 | Wave 1                           | emailed
       7 | Wave 1                           | emailed
       8 | Wave 1                           | emailed
(9 rows)

@skyler
Copy link
Author

skyler commented Feb 11, 2014

waves = session.query(Wave).all()
from pprint import pprint
pprint(waves)
for wave in waves:
    print wave.__class__.__name__ + " " + wave.type

produces

[<__main__.Wave object at 0x2324b50>,
 <__main__.Wave object at 0x2324d50>,
 <__main__.Wave object at 0x2324dd0>,
 <__main__.Wave object at 0x2324e50>,
 <__main__.Wave object at 0x2324ed0>,
 <__main__.Wave object at 0x2324f90>,
 <__main__.Wave object at 0x2329090>,
 <__main__.Wave object at 0x2329150>,
 <__main__.Wave object at 0x2329210>]
Wave emailed
Wave emailed
Wave emailed
Wave emailed
Wave emailed
Wave emailed
Wave emailed
Wave emailed
Wave emailed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment