gpt4 book ai didi

python - post_save.disconnect 根本不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 16:30:44 26 4
gpt4 key购买 nike

我试图让 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)

问题出在哪里?我这样做了,但我仍然收到两个警报 - 新订单已编辑订单

最佳答案

问题在于您两次收听同一个信号。

@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

关于python - post_save.disconnect 根本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37622183/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com