I have the following code:
session = scoped_session(sessionmaker(autocommit=False, autoflush=True, bind=engine))
Base = declarative_base()
Base.query = ses
Check out the SQLAlchemy documentation on reconstruction:
The SQLAlchemy ORM does not call
__init__
when recreating objects from database rows. The ORM’s process is somewhat akin to the Python standard library’s pickle module, invoking the low level__new__
method and then quietly restoring attributes directly on the instance rather than calling__init__
.If you need to do some setup on database-loaded instances before they’re ready to use, you can use the @reconstructor decorator to tag a method as the ORM counterpart to
__init__
. SQLAlchemy will call this method with no arguments every time it loads or reconstructs one of your instances. This is useful for recreating transient properties that are normally assigned in your__init__
:
from sqlalchemy import orm
class MyMappedClass(object):
def __init__(self, data):
self.data = data
# we need stuff on all instances, but not in the database.
self.stuff = []
@orm.reconstructor
def init_on_load(self):
self.stuff = []
When obj = MyMappedClass() is executed, Python calls the
__init__
method as normal and the data argument is required. When instances are loaded during a Query operation as in query(MyMappedClass).one(),init_on_load
is called.