开发者

Registering Multiple Signals in Django

I'm trying to register multiple signals on one model. It seems that as I register an additional signal, it removes the previous signal.

from django.dispatch import receiver
from django.db.models.signals import post_save,post_delete
from my.app.models import Resource


@receiver(post_save,sender=Resource)
def ResourceSaved(sender,**kwargs):
    print "Saved"

@receiver(post_delete,sender=Resource)
def ResourceSaved(sender,**kwargs):
    print "Deleted"

I've taken a look around the docs, but I keep finding details on how to create custom signals in a class开发者_StackOverflow formate. Not how to register in class format.

I would imagine I can do something like this:

@reciver(sender=Resource)
class SignalAnsweringMachine(object):
    def post_delete(self,**kwargs):
        print "delete"
    def post_save(self,**kwargs):
        print "save"

Thanks for your help in advance.


You are (probably unintentionally) redefining ResourceSaved. Try this instead:

@receiver(post_save,sender=Resource)
def ResourceSaved(sender,**kwargs):
    print "Saved"

@receiver(post_delete,sender=Resource)
def ResourceDeleted(sender,**kwargs):
    print "Deleted"


Since the merge of #18454 released in Django 1.5 you can connect more than one signal by supplying a list of signals:

@receiver([post_save, post_delete], sender=Resource)
def ResourceSaved(sender, **kwargs):
    pass


I use this short form to register two or more handlers.

In my case I clear cached categories list.

from django.dispatch import receiver
from django.db.models.signals import post_save, post_delete
from ..models import Category

all_categories = []

# Post save handler for Category model to clear "all_categores" variable
@receiver(post_save, sender=Category)
@receiver(post_delete, sender=Category)
def post_save_category(sender, **kwargs):
    # clean cached categories
    global all_categories
    all_categories = []
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜