post_save.disconnect根本不起作用

时间:2016-06-03 19:38:28

标签: python django django-models django-signals

我试图让Django在一个案例中不发送信号。在模型Delivery的新实例(创建Job之后)作为模型Job的属性添加时,我不想发送信号,因为信号应警告管理员Job已被编辑。

不幸的是,我无法使其发挥作用。

@receiver(post_save,sender=Job) # When Job is created or edited
def alert_admin(sender,instance,created,**kwargs):
    if created:
        email.AdminNotifications.new_order(instance)
    else:
        email.AdminNotifications.edited_order(instance)

@receiver(post_save,sender=Job) # When job is created, I want to create a delivery object as an attribute of Job
def create_delivery(sender,instance,created,**kwargs):
    if created:
        delivery,created_delivery = Delivery.objects.get_or_create(job=instance)
        instance.delivery = delivery
        delivery.save()
        post_save.disconnect(alert_admin)
        instance.save() # I DONT WANT TO SEND SIGNAL IN THIS CASE
        post_save.connect(alert_admin)

问题出在哪里?我这样做但我仍然收到两个提醒 - New OrderEdited Order

1 个答案:

答案 0 :(得分:1)

问题是你正在听两次相同的信号。

@receiver(post_save,sender=Job) # When Job is created or edited
def alert_admin(sender,instance,created,**kwargs):
    ###

@receiver(post_save,sender=Job):
def create_delivery(sender,instance,created,**kwargs):
   ###

您认为首先会调用create_delivery。但这似乎并没有发生。似乎首先调用alert_admin。因此,你在create_delivery中发出的禁用信号只会浪费。

Django不对触发信号的顺序提供任何保证或控制(what's the order of post_save receiver in django?

您可以向实例添加一个简单的标志,告诉信号处理器该信号不需要进一步处理。

if hasattr(instance,'signal_processed'):
     return
else:
    # do whatever processing
    instance.signal_processed = True