3

我想通过处理 post_save、delete 和 init 信号来跟踪我的模型及其 CRUD 操作,然后将有关此操作处理的条目保存到数据库中。

def handle_model_saved(sender, **kwargs):
  """Trap the signal and do whatever is needed"""
  entry=CRUD_Storage()
  entry.entry='Object \"'+sender._meta.module_name+'\" was saved.'
  entry.save()

然后有趣的是,它是保存的递归......

我创建了模型 CRUD_Storage,我想阻止它发送诸如 pre(post)init、delete、save 之类的信号。

4

2 回答 2

3

我认为你不能阻止 Django 发送这些信号。

但是,您可以调整处理程序以不记录CRUD_Storage模型的保存。

def handle_model_saved(sender, **kwargs):
    """Trap the signal and do whatever is needed"""
    if sender == CRUD_Storage:
        # return early to prevent recursion of saves
        return
    entry=CRUD_Storage()
    entry.entry='Object \"'+sender._meta.module_name+'\" was saved.'
    entry.save()
于 2012-01-07T14:50:17.803 回答
1

Here is a DRY way of dismissing signals.

If you want to dismiss a signal to avoid recursion, a simple way to go is to set an attribute on the current instance to prevent upcoming signals firing.

This can be done using a simple decorator that checks if the given instance has the 'skip_signal' attribute, and if so prevents the method from being called:

from functools import wraps

def skip_signal():
    def _skip_signal(signal_func):
        @wraps(signal_func)
        def _decorator(sender, instance, **kwargs):
            if hasattr(instance, 'skip_signal'):
                return None
            return signal_func(sender, instance, **kwargs)  
        return _decorator
    return _skip_signal

We can now use it this way:

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=MyModel)
@skip_signal()
def my_model_post_save(sender, instance, **kwargs):
    # you processing
    pass

m = MyModel()
# Here we flag the instance with 'skip_signal'
# and my_model_post_save won't be called
# thanks to our decorator, avoiding any signal recursion
m.skip_signal  = True
m.save()

Hope This helps.

于 2014-11-27T23:14:48.520 回答