I have code structured something like this:
project
--app
----utils
------util.py
----__init__.py
----models.py
--tests
----__init__.py
Within tests/__init__.py I have code that initializes the application (flask if that matters) and database session by importing it all from app/__init__.py. I can create an instances of models, query, and access backrefs fine within tests/__init__.py. Code of the following form works fine:
objs = SomeModel.query.all()
for o in objs:
o.backref
However, if I do something like:
from utils.util import some_function
objs = SomeModel.query.all()
for o in objs:
some_function(o)
where some_function just accesses a backref
def some_function(obj):
obj.backref
I get an error like DetachedInstanceError: Parent instance <SomeModel at 0x2c1fe10> is not bound to a Session; lazy load operation of attribute 'backref' cannot proceed
Reading the sqlalchemy docs suggests that I need to re-associate the object to a database sesssion. I did that and it looks like it works (i.e. running the function doesn't fail with the previous error):
import db_session
def some_function(obj):
db_session.add(obj)
obj.backref
So when exactly does an object get detached? It seems like just passing the object to a function in another module detaches it from a session. Does the object not know about the sqlalchemy session it is associated with? I'm trying to avoid doing db_session.add(obj)
which seems like a lot of boilerplate code.