Create a gist now

Instantly share code, notes, and snippets.

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import event
Base = declarative_base()
Session = sessionmaker()
class EmployeeType(Base):
__tablename__ = 'employee_type'
id = Column(Integer(), primary_key=True)
name = Column(String(20))
class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer(), primary_key=True)
type_id = Column(Integer(), ForeignKey(
type = relationship(EmployeeType)
_pending_type_name = None
def _attach_pending_type(self):
if self._pending_type_name is not None:
self.type = session.query(EmployeeType).filter_by(name=self._pending_type_name).one()
self._pending_type_name = None
def type_name(self):
if self._pending_type_name is not None:
return self._pending_type_name
if self.type is not None:
return None
def type_name(self, value):
if value is None:
self.type = None
self._pending_type_name = value
session = Session.object_session(self)
if session is not None:
@event.listens_for(Session, 'after_attach')
def _after_attach(session, instance):
if isinstance(instance, Employee):
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment