Skip to content

Instantly share code, notes, and snippets.

@blt

blt/models.py

Created Jul 17, 2010
Embed
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('instructor.id'))
)
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
self.name = name
def hash(self):
return {u"abbreviation": self.abbrv, u"name": self.name}
def __repr__(self):
return "<Dept('%(abbreviation)s','%(name)s')>" % \
self.hash()
class Inst(Base,Hasher):
__tablename__ = 'instructor'
id = Column(String, primary_key=True)
fname = Column(String)
lname = Column(String)
departments = relationship('Dept', secondary=dept_insts,
backref='instructor')
def __init__(self, id, fname, lname, depts=None):
self.id = id
self.fname = fname
self.lname = lname
if not depts:
self.departments = []
else:
self.departments = depts
def hash(self):
return {u'fname': self.fname, u'lname': self.lname,
u'id': self.id,
u'departments': [d.hash() for d in self.departments]}
def __repr__(self):
return "<Inst('%(id)s', '%(fname)s', '%(lname)s')>" % \
self.hash()
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': self.name, u'id': [self.dept, self.id],
u'prerequisites': [c.hash() for c in self.prereq]}
def __repr__(self):
return "<Class('%(name)s', '%(id)s'>" % \
self.hash()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment