在Django中注册多个信号

时间:2011-05-07 18:06:50

标签: python django signals

我正在尝试在一个型号上注册多个信号。看来,当我注册一个额外的信号时,它会删除先前的信号。

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"

我已经浏览了文档,但我一直在寻找如何在类合成中创建自定义信号的详细信息。不是如何以班级格式注册。

我想我可以做这样的事情:

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

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:11)

您(可能是无意中)重新定义了ResourceSaved。试试这个:

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

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

答案 1 :(得分:6)

我使用这个简短形式注册两个或更多处理程序。

就我而言,我清除了缓存的类别列表。

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 = []

答案 2 :(得分:0)

您现在可以在信号接收器中使用以下语法:

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