首页 > 解决方案 > 如何加载所有 sqlalchemy orm 实例属性,以便可以安全地删除它们

问题描述

在 sqlalchemy 中,是否可以强制加载我的 orm 实例的所有属性,以便可以安全地删除?

我要处理的具体情况是我写了一个装饰器

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

这导致错误Instance <MyInstance at 0x7f22d2831240> is not bound to a Session; attribute refresh operation cannot proceed。据我了解,这是由延迟加载的属性或关系引起的,调用者将无法访问它们,因为它们在装饰器中已被删除。

我可以想象解决这个问题的一种方法是在调用expunge_all(). 有没有办法在 sqlalchemy 中做到这一点?

标签: pythonsqlalchemy

解决方案


推荐阅读