我试图让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 Order
和Edited Order
。
答案 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