Created
July 3, 2013 20:26
-
-
Save deontologician/5922496 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy import * | |
from sqlalchemy.orm import * | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy.ext.associationproxy import association_proxy | |
Base = declarative_base() | |
class Machine(Base): | |
__tablename__ = 'machines' | |
__table_args__ = {'sqlite_autoincrement': True} | |
machine_id = Column(Integer, primary_key=True) | |
widgets = relationship('Widget') | |
class Widget(Base): | |
__tablename__ = 'widgets' | |
__table_args__ = {'sqlite_autoincrement': True} | |
widget_id = Column(Integer, primary_key=True) | |
machine_id = Column(Integer, ForeignKey('machines.machine_id'), nullable=False) | |
_gadgets = relationship('Gadget') | |
gadgets = association_proxy('_gadgets', 'json_repr', | |
creator=lambda kwargs: Gadget(**kwargs)) | |
class Gadget(Base): | |
__tablename__ = 'gadgets' | |
__table_args__ = {'sqlite_autoincrement': True} | |
gadget_id = Column(Integer, primary_key=True) | |
widget_id = Column(Integer, ForeignKey('widgets.widget_id'), nullable=False) | |
machine_id = Column(Integer, nullable=False) | |
a = Column(String) | |
b = Column(String) | |
c = Column(Integer) | |
@property | |
def json_repr(self): | |
return dict(a=self.a, b=self.b, c=self.c) | |
if __name__ == '__main__': | |
engine = create_engine('sqlite:///:memory:', echo=True) | |
Base.metadata.bind = engine | |
Base.metadata.create_all() | |
session = sessionmaker(bind=engine)() | |
m = Machine() | |
w = Widget() | |
session.add(m) | |
m.widgets.append(w) | |
w.gadgets.append(dict(a='1', b='2')) | |
session.commit() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment