public
Created

  • Download Gist
column_rel_with_events.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
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(EmployeeType.id))
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
 
@property
def type_name(self):
if self._pending_type_name is not None:
return self._pending_type_name
if self.type is not None:
return self.type.name
return None
 
@type_name.setter
def type_name(self, value):
if value is None:
self.type = None
else:
self._pending_type_name = value
session = Session.object_session(self)
if session is not None:
self._attach_pending_type()
 
@event.listens_for(Session, 'after_attach')
def _after_attach(session, instance):
if isinstance(instance, Employee):
instance._attach_pending_type()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.