Skip to content

anonymous /column_rel_with_events.py
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.