Created
March 2, 2013 20:02
-
-
Save groner/5073024 to your computer and use it in GitHub Desktop.
sqlalchemy demonstration at beSwarm
This file contains hidden or 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 ( | |
create_engine, | |
MetaData, | |
Table, | |
Column, | |
ForeignKey, | |
Integer, | |
Text) | |
def main(): | |
engine = create_engine('sqlite:///') | |
metadata = MetaData() | |
foo_table = Table('foo', metadata, | |
Column('id', Integer(), primary_key=True), | |
Column('blah', Text())) | |
bar_table = Table('bar', metadata, | |
Column('id', Integer(), primary_key=True), | |
Column('foo_id', Integer(), ForeignKey(foo_table.c.id), | |
nullable=False), | |
Column('blah', Text())) | |
foo_table.create(engine) | |
bar_table.create(engine) | |
engine.execute(foo_table.insert().values( | |
id=1, blah='bah blah blah.')) | |
engine.execute(bar_table.insert().values( | |
foo_id=1, blah='beep bop boop')) | |
print foo_table.join(bar_table).select(use_labels=True) | |
for row in engine.execute(foo_table.join(bar_table).select(use_labels=True)): | |
print 'Row #{0.foo_id}: blah={0.foo_blah!r} bar.blah={0.bar_blah!r}'.format(row) | |
if __name__ == '__main__': | |
main() |
This file contains hidden or 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 ( | |
create_engine, | |
Column, | |
Integer, | |
Text, | |
ForeignKey) | |
from sqlalchemy.orm import ( | |
sessionmaker, | |
relationship) | |
from sqlalchemy.ext.declarative import declarative_base | |
def main(): | |
engine = create_engine('sqlite:///') | |
Session = sessionmaker() | |
Base = declarative_base() | |
class Foo(Base): | |
__tablename__ = 'foo' | |
id = Column(Integer(), primary_key=True) | |
blah = Column(Text(), nullable=False) | |
class Bar(Base): | |
__tablename__ = 'bar' | |
id = Column(Integer(), primary_key=True) | |
foo_id = Column(Integer(), ForeignKey(Foo.id), nullable=False) | |
blah = Column(Text(), nullable=False) | |
foo = relationship(Foo) | |
Base.metadata.create_all(engine) | |
Session.configure(bind=engine) | |
engine.echo = True | |
session = Session() | |
bar = Bar(blah='banana', foo=Foo(blah='dingus')) | |
session.add(bar) | |
for foo in session.query(Foo): | |
print foo | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment