如果书写了多个信号,可能会出现互相干扰的情况。为了防止这种情况的发生,我们可以手动控制信号的断开与连接。
# 导入依赖
from django.db.models.signals import post_save
from django.dispatch import receiver
def disconnect_signals():
post_save.disconnect(信号1, sender=模型表1)
post_save.disconnect(信号2, sender=模型表2)
# 设置weak=False解除弱引用,防止被垃圾回收机制清理
def connect_signals():
post_save.connect(信号1, sender=模型表1, weak=False)
post_save.connect(信号2, sender=模型表2, weak=False)
# 在信号中使用
@receiver(post_save, sender=模型表1)
def 信号1(sender, instance, created, **kwargs):
disconnect_signals() # 关闭所有信号
pass # 书写逻辑
connect_signals() # 重新连接信号
@receiver(post_save, sender=模型表2)
def 信号2(sender, instance, created, **kwargs):
disconnect_signals() # 关闭所有信号
pass # 书写逻辑
connect_signals() # 重新连接信号
标签:干扰,sender,Django,signals,信号,disconnect,post,save
From: https://www.cnblogs.com/wellplayed/p/18623497