Skip to content

Instantly share code, notes, and snippets.



Created Jul 17, 2010
What would you like to do?
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String
from sqlalchemy import ForeignKey, Boolean
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:////tmp/bunsen.db', echo=False)
Base = declarative_base()
metadata = Base.metadata
# association table(s)
dept_insts = Table('department_instructors', metadata,
Column('dept_id', String, ForeignKey('department.abbrv')),
Column('inst_id', Integer, ForeignKey(''))
class Hasher(object):
def hash(self):
raise NotImplemented
class Dept(Base,Hasher):
__tablename__ = 'department'
abbrv = Column(String, primary_key=True)
name = Column(String)
def __init__(self, abbrv, name):
self.abbrv = abbrv = name
def hash(self):
return {u"abbreviation": self.abbrv, u"name":}
def __repr__(self):
return "<Dept('%(abbreviation)s','%(name)s')>" % \
class Inst(Base,Hasher):
__tablename__ = 'instructor'
id = Column(String, primary_key=True)
fname = Column(String)
lname = Column(String)
departments = relationship('Dept', secondary=dept_insts,
def __init__(self, id, fname, lname, depts=None): = id
self.fname = fname
self.lname = lname
if not depts:
self.departments = []
self.departments = depts
def hash(self):
return {u'fname': self.fname, u'lname': self.lname,
u'departments': [d.hash() for d in self.departments]}
def __repr__(self):
return "<Inst('%(id)s', '%(fname)s', '%(lname)s')>" % \
class Class(Base,Hasher):
__tablename__ = 'classes'
id = Column(Integer, primary_key=True)
dept = Column(Integer, ForeignKey('department.abbrv'), primary_key=True)
name = Column(String, nullable=False)
prereq = None # Needs to be a list of Class refs.
def hash(self):
return {u'name':, u'id': [self.dept,],
u'prerequisites': [c.hash() for c in self.prereq]}
def __repr__(self):
return "<Class('%(name)s', '%(id)s'>" % \
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment