Django:在queryset.update上发出信号 [英] Django: Signal on queryset.update

查看:237
本文介绍了Django:在queryset.update上发出信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您使用 queryset.delete()方法,则Django正在发送pre / post_delete信号,但不应该,然后在<$上发送pre / post_save c $ c> queryset.update()?

Django is sending the pre/post_delete signals if you are using the queryset.delete() method, but shouldn't it then also send pre/post_save on queryset.update()?

推荐答案

也许应该,但是没有。 t。 .update()不会对QuerySet中的各个对象调用 .save()方法,而是进行更新只需一次SQL调用即可完成所有操作(发生更新时)。由于它不使用 .save(),因此调用保存前和保存后信号是不一致的。我当然可以设想用例中可能有人希望这样做,但是我也可以设想用例中不希望这样做。在我看来,不调用保存前和保存后信号是正确的行为,因为它为程序员留下了更大的灵活性。手动触发这些信号并不难,并且我认为与要求程序员记住断开信号以避免不必要的行为相比,要求程序员记住触发信号以获得所需的行为绝对是一个更好的设计决策。

Perhaps it should, but it doesn't. .update() does not call the .save() method on the individual objects in the QuerySet, and instead updates the all in a single SQL call (UPDATE, as it happens). Since it doesn't use .save(), it would be inconsistent for it to call the pre- and post-save signals. I can certainly envision use-cases in which one might want it to do so, but I can also envision cases in which one wouldn't. It seems to me that not calling the pre- and post-save signals is the correct behavior here as it leaves more flexibility for the programmer. It's not hard to trigger those signals manually, and I think it's definitely a better design decision to ask programmers to remember to trigger the signals to get desired behavior than asking them to remember to disconnect the signals to avoid undesired behavior.

这篇关于Django:在queryset.update上发出信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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