Django - 我如何_not_发送信号? [英] Django - how do I _not_ dispatch a signal?

查看:116
本文介绍了Django - 我如何_not_发送信号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的模型写了一些智能的通用计数器和管理器(以避免选择计数查询等)。因此,我对post_save有一些沉重的逻辑。



当不需要时,我想防止处理信号。
我猜想完美的界面是:

  instance.save(dispatch_signal = False)

如何实现?






更新



如果有任何人感兴趣,有关我在做什么的更多信息:


  1. 通用计数器存储在单独的表中

  2. 每当Django分页一个对象列表时,它会调用自定义的覆盖count()方法经理,它基本上检索适当的对象类的静态计数器值。

  3. 信号触发计数器更新的逻辑,这是有点复杂的,因为它检查了相关模型的许多方面(即它有以生成基于嵌套类别树的可见性属性)。我不能把这个逻辑放在Model.save()中,因为一个计数器依赖于许多不同的模型。我想把这个逻辑放在一块,而不是碎片的传播。

  4. 我正在对我的一些模型进行非规范化,所以我重写(重复)表中的某些值。 li>
  5. 为了测试目的,我运行我的小命令扩展名 - Dilla ,填写随机数据。

  6. 我注意到不需要的信号触发,因此我希望他们有条件地运行。

希望很清楚。请问我的语言错误。

解决方案

一个简单肮脏的解决方案是:



来自django.db.models.signals的$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $



post_save.disconnect(my_post_save_handler)
实例。 save()
post_save.connect(my_post_save_handler)

否则我强烈建议您移动逻辑进入您的模型的 save()方法。


I wrote some smart generic counters and managers for my models (to avoid select count queries etc.). Therefore I got some heavy logic going on for post_save.

I would like to prevent handling the signal when there's no need to. I guess the perfect interface would be:

instance.save(dispatch_signal=False)

How can I accomplish this?


Update

More information about what I'm doing, if anyone's interested:

  1. Generic counters are stored in a separate table
  2. Every time Django paginates an object list, it calls overriden count() method of my custom manager, which basically retrieves the static counter value for appropriate object class.
  3. Signals trigger the logic of counters update, which is a bit complicated since it checks many aspects of related models (i.e. it has to generate a visibility property based on a nested category tree). I can't put this logic in Model.save() because one counter depends on many different models. I'd like to have that logic in one piece, instead of fragments spread around.
  4. I am denormalizing some of my models, so I rewrite (duplicate) certain values across tables.
  5. For testing purposes I run my little command-extension -- Dilla, to populate random data around.
  6. I've noticed unwanted signals triggering, therefore I'd like them to run conditionally.

Hope it's clear enough. Excuse my language mistakes.

解决方案

A quick and dirty solution would be:

from django.db.models.signals import post_save
from somewhere_in_my_app import my_post_save_handler

post_save.disconnect(my_post_save_handler)
instance.save()
post_save.connect(my_post_save_handler)

But otherwise i strongly recommend moving your logic into the save() method of your model.

这篇关于Django - 我如何_not_发送信号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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