How to load all sqlalchemy orm instance attributes so that they can be safely expunged

Viewed 167

In sqlalchemy, is it possible to force loading all attributes of my orm instance, such that the can be safely expunged?

The specific case I'm trying to deal with is that I've written a decorator

def auto_session(func):
    """
    Decorate a function that takes a 'session' keyword argument. If a
    session is provided, this decorator does nothing; if no session is
    provided, one will be created an committed.

    Before closing the auto-session, ``expunge_all()`` is called. Be aware
    that this means subsequent modifications to these object instances will
    NOT be reflected in the database.
    """

    def inner(dbi, *args, **kwargs):
        if "session" in kwargs:
            return func(*args, **kwargs)
        else:
            kwargs["session"] = Session()
            ret = func(*args, **kwargs)
            kwargs["session"].commit()
            kwargs["session"].expunge_all()
            kwargs["session"].close()
            return ret

    return inner

which results in the error Instance <MyInstance at 0x7f22d2831240> is not bound to a Session; attribute refresh operation cannot proceed. It's my understanding that it's caused by lazy-loaded attributes or relationships, which caller won't be able to access because they're expunged in the decorator.

One way I could imagine addressing this is to force loading prior to the call to expunge_all(). Is there a way to do that in sqlalchemy?

0 Answers
Related