from sqlalchemy import *
import os
# with constructor
class FooDoesntWork(object):
def __init___(self, id, name):
self.id = id
self.name = name
def __repr__(self):
return '%s, %s' % (self.id, self.name)
#no constructor
class FooWorks(object):
def set(self, id, name):
self.id = id
self.name = name
def __repr__(self):
return '%s, %s' % (self.id, self.name)
# to use the no-constructor class, set Foo = FooWorks
# to use the class with a constructor, set Foo = FooDoesntWork
Foo = FooDoesntWork # <== change this for different results
# delete the database if it exists
try:
os.remove('foo.db')
except:
pass
db = create_engine('sqlite:///foo.db')
metadata = BoundMetaData(db)
metadata.engine.echo = True
foo_table = Table('foo', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(40)))
foo_mapper = mapper(Foo, foo_table)
session = create_session()
foo_table.create()
# here we create the object differently based on
# which Foo* class we're using
if Foo is FooDoesntWork:
# class with __init__ constructor - won't save
foo = Foo(100, 'bob')
elif Foo is FooWorks:
# class without __init__ constructor will save
foo = Foo()
foo.set(100, 'bob')
session.save(foo)
session.flush()
# try to retrieve the saved object
foo_query = session.query(Foo)
gotten = foo_query.get_by(id=100)
# if using FooWorks, this prints object foo
# if using FooDoesntWork, this prints 'None'
print gotten