How to disable SQLAlchemy lazy loads on detached instance relationships?

Viewed 306

I've developed a JDO-like Fetch Group feature in Python with SQLAlchemy to control the pruning of object graphs for marshalling web service responses.

During this process I detach the instances using session.expunge(entity)

The issue is that when the JSON marshaller or pydantic accesses an instance attribute relationship which was not loaded yet, even though the instance is detached, the SQLAlchemy lazy loading still kicks in for that attribute and fails because the instance is not bound to a session anymore (obviously):

DetachedInstanceError("Parent instance <MyClass at 0x1439051f0> is not bound to a Session; lazy load operation of attribute 'relation' cannot proceed")

So, my first question, is why are the lazy loaders not disabled when an instance is detached as it doesn't make sense to me.

Secondly, if that is a "feature", how can I disable or work-around lazy loaders to prevent this error and let the attribute relationship in question appear None to the marshaller?

I have found that setting self.__dict__['relation'] = None helps in some circumstance in fooling the lazy loaders in not kicking in but it does not always work unfortunately...

1 Answers

Concerning your second question, you could use make_transient (see here)

The function will remove its association with any Session as well as its InstanceState.identity. The effect is that the object will behave as though it were newly constructed, except retaining any attribute / collection values that were loaded at the time of the call.

Related