Skip to content

Instantly share code, notes, and snippets.

@vinvinod
Created August 3, 2020 11:27
Show Gist options
  • Save vinvinod/d202e29456aeefad864736a3ddca63ef to your computer and use it in GitHub Desktop.
Save vinvinod/d202e29456aeefad864736a3ddca63ef to your computer and use it in GitHub Desktop.
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Item(Base):
__tablename__ = "item"
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.VARCHAR(128))
status = sa.Column(
sa.Enum("DRAFT", "PUBLISHED"), default="DRAFT", server_default=sa.text("'DRAFT'"), nullable=False,
)
class DraftItem(Item):
__mapper_args__ = {
"polymorphic_on": "status",
"polymorphic_identity": "DRAFT",
}
class PublishedItem(Item):
__mapper_args__ = {
"polymorphic_on": "status",
"polymorphic_identity": "PUBLISHED",
}
engine = sa.create_engine("sqlite:///:memory:", echo=False)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
draft_item = DraftItem(name="draft-1")
published_item = PublishedItem(name="published-1")
session.add(published_item)
session.add(draft_item)
session.commit()
print("\nDraft Items")
print("====================")
for f in session.query(DraftItem):
print(f.name, f.status, f.id)
print("\nPublished Items")
print("====================")
for f in session.query(PublishedItem):
print(f.name, f.status, f.id)
print("\nAll Items")
print("====================")
for f in session.query(Item):
print(f.name, f.status, f.id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment