1. synchronize_session参数

参数可选False、'fetch'、'evaluate';官网说明

False - don’t synchronize the session. This option is the most efficient and is reliable once the session is expired, which typically occurs after a commit(), or explicitly using expire_all(). Before the expiration, objects that were updated or deleted in the database may still remain in the session with stale values, which can lead to confusing results.

'fetch' - Retrieves the primary key identity of affected rows by either performing a SELECT before the UPDATE or DELETE, or by using RETURNING if the database supports it, so that in-memory objects which are affected by the operation can be refreshed with new values (updates) or expunged from the Session (deletes). Note that this synchronization strategy is not available if the given update() or delete() construct specifies columns for UpdateBase.returning() explicitly.

'evaluate' - Evaluate the WHERE criteria given in the UPDATE or DELETE statement in Python, to locate matching objects within the Session. This approach does not add any round trips and in the absence of RETURNING support is more efficient. For UPDATE or DELETE statements with complex criteria, the 'evaluate' strategy may not be able to evaluate the expression in Python and will raise an error. If this occurs, use the 'fetch' strategy for the operation instead.

具体参见:​​session_basics​

需要看翻译,可以参考: ​​sqlalchemy session 执行 delete 时 synchronize_session 策略​

2. 个人理解

  • 选填False, 意味着不同步session, 即不论对应session的identity_map中是否存在这次更新或删除的数据,identity_map中的数据都不改变。优点:性能好,缺点:如果直接从identity_map中获取数据,会发现还是旧数据。
  • 选填'fetch', 意味着同步session, identity_map中对应的数据会自动更新或删除。 优点:identity_map中始终都是最新数据, 缺点:性能差(因为可能会触发查询操作,用以更新identity_map中数据,使用数据库mysql时就是这种情况)
  • 选填'evaluate'(默认值), 意味着同步session, identity_map中对应的数据会自动更新或删除。优点:identity_map中始终都是最新数据, 缺点:不稳定,查询条件复杂时会报错,因为其用python对where条件进行估值,不一定总是可行。