脏属性会影响会话.查询

2024-04-26 13:15:50 发布

您现在位置:Python中文网/ 问答频道 /正文

当我创建sqlalchemy会话并更改某个模型的某些属性时,在会话上的任何flushcommit之前进行query时,这些更改是否适用?你知道吗

我找不到任何适当的文件来说明这个状态。你知道吗

具体来说,我是在尝试在模型创建/更新的事件侦听器中验证DB不变量时遇到这个问题的。我知道我在session.dirty中有脏模型,除了我制作的任何标准session.query()之外,我还需要手动查询它们吗?你知道吗


Tags: 文件模型db标准属性sqlalchemysession状态
1条回答
网友
1楼 · 发布于 2024-04-26 13:15:50

“脏属性会影响session.query”的简短答案是no,如"Is the Session a cache?"中所述:

However, it doesn’t do any kind of query caching. This means, if you say session.query(Foo).filter_by(name='bar'), even if Foo(name='bar') is right there, in the identity map, the session has no idea about that. It has to issue SQL to the database, get the rows back, and then when it sees the primary key in the row, then it can look in the local identity map and see that the object is already there.

实际上,这并不是那么简单,因为在其默认配置中,SQLAlchemy会定期将保存在Session中的更改刷新到数据库中。这被称为autoflush,它确保向数据库发出的查询能够观察到它在Session中的状态。你知道吗

"What does the Session do ?"中还指出

It provides the entrypoint to acquire a Query object, which sends queries to the database using the Session object’s current database connection,

因此,如果您禁用了自动刷新,或者处于无法进行刷新的上下文中,则必须手动处理脏对象。你知道吗

相关问题 更多 >