python - 如何加载所有 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 中做到这一点?
解决方案
推荐阅读
- javascript - 通过“/i18n/setlang/”更改语言 ajax POST 在 Firefox 上没有任何作用
- dataframe - 如果满足条件,则重命名某列中某行的某些值
- asp.net - 使用 Serilog 将日志写入文件不起作用
- c# - 公开枚举
- r - 如何将数据框形式的条件传递给 dplyr::filter
- r - 使用 R 的堆叠累积直方图/面积图
- batch-file - 批量移动不处理子文件夹
- javascript - 使用嵌套表单的 jQuery SheepIt 演示索引错误
- react-native - 如何在选项卡屏幕中访问传递给 TabNavigator 的道具?
- c++ - 如何在结构/类中调用对象的可选实例