sqlalchemy 监听after_update事件无效

查看:546
本文介绍了sqlalchemy 监听after_update事件无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

大家好。我正在练习使用sqlalchemy的事件监听。

代码监听after_insert, before_insert都没有问题,但使用after_update却无效,虽然看了官方文档,但还是十分模糊。文档提到有几种情况UPDATE状态不会发生。

If, at update time, no column-based attributes have any net changes,
no UPDATE statement will be issued. This means that an instance being
sent to after_update() is not a guarantee that an UPDATE statement has
been issued.

但我不知道我是否处于这类情况下。我实际的需求是这样的:当一条评论被管理员通过后,通过注册的监听after_update事件给用户通知。然而运行代码什么都没有发生,我猜想是UPDATE没有被监听到。但是不知道为什么,求教。

解决方案

后来看了文档还是解决了

The Query.update() method is a bulk operation, which bypasses ORM
unit-of-work automation in favor of greater performance. Please read
all caveats and warnings below.

The MapperEvents.before_update() and MapperEvents.after_update() events are not invoked from this method. Instead, the
SessionEvents.after_bulk_update() method is provided to act upon a
mass UPDATE of entity rows.

所以有两种办法解决这个问题,

  1. 使用SessionEvents.after_bulk_update()

  2. 使用Attribute Event中的set方法,需要将原来update的操作改成类似susan.age = 18的更新方式

这篇关于sqlalchemy 监听after_update事件无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆