Skip to content

Instantly share code, notes, and snippets.

@lmyyao
Created August 1, 2016 06:57
Show Gist options
  • Save lmyyao/31094871cefbcbf7d46444073f157046 to your computer and use it in GitHub Desktop.
Save lmyyao/31094871cefbcbf7d46444073f157046 to your computer and use it in GitHub Desktop.
sqlalchemy PostgreSQLInheritance
# encoding=utf8
'''
https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/PostgreSQLInheritance
'''
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import as_declarative, declared_attr
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine('postgresql:///test', convert_unicode=True, echo=False)
Session = sessionmaker(autocommit=False,
autoflush=False,
bind=engine)
session = scoped_session(Session)
from sqlalchemy import Column, Integer, TIMESTAMP, func, String
from sqlalchemy import event
@as_declarative()
class Base(object):
@declared_attr
def __tablename__(cls):
return cls.__name__.lower() + 's'
id = Column(Integer, primary_key=True)
created_date = Column(TIMESTAMP, nullable=False, server_default=func.current_timestamp())
updated_date = Column(TIMESTAMP, nullable=False, server_default=func.current_timestamp(),
onupdate=func.current_timestamp())
class T1(Base):
__tablename__ = 't1'
name = Column(String(20), nullable=False)
age = Column(Integer, nullable=False)
@event.listens_for(T1.__table__, 'after_create')
def create_child_tables(target, connection, **kw):
print(target, kw)
connection.execute("""
create table t2 (
flag boolean default false
) inherits(t1)
""")
Base.metadata.create_all(bind=engine)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment