Parent instance is not bound to a Session; lazy load operation of attribute ’account’ cannot proceed

While trying to do the following operation:

for line in blines:
    line.account = get_customer(line.AccountCode)

I am getting an error while trying to assign a value to line.account:

DetachedInstanceError: Parent instance <SunLedgerA at 0x16eda4d0> is not bound to a       Session; lazy load operation of attribute 'account' cannot proceed

Am I doing something wrong??

Answers


"detached" means you're dealing with an ORM object that is not associated with a Session. The Session is the gateway to the relational database, so anytime you refer to attributes on the mapped object, the ORM will sometimes need to go back to the database to get the current value of that attribute. In general, you should only work with "attached" objects - "detached" is a temporary state used for caching and for moving objects between sessions.

See Quickie Intro to Object States, then probably read the rest of that document too ;).


I had the same problem with Celery. Adding lazy='subquery' to relationship solved my problem.


I encountered this type of DetachedInstanceError when I prematurely close the query session (that is, having code to deal with those SQLAlchemy model objects AFTER the session is closed). So that's one clue to double check no session closure until you absolutely don't need interact with model objects, I.E. some Lazy Loaded model attributes etc.


I had the same problem when unittesting.

The solution was to call everything within the "with" context:

with self.app.test_client() as c:
    res = c.post('my_url/test', data=XYZ, content_type='application/json')

Then it worked.

Adding the lazy attribute didn't work for me.


Need Your Help

Benefit of using Parcelable instead of serializing object

android serialization bundle parcelable

As I understand, Bundle and Parcelable belongs to the way Android performs serialization in. It is used for example in passing data between activities. But I wonder, if there are any benefits in us...

UILabel wrong word wrap in iOS 11

ios iphone uilabel ios11

I have problem with application using XIBs without autolayout. I don't know if this is important information.