gpt4 book ai didi

django - 断开模型的信号并在 django 中重新连接

转载 作者:行者123 更新时间:2023-11-28 19:37:02 27 4
gpt4 key购买 nike

我需要对模型进行保存,但我需要在保存之前断开一些信号接收器。

我的意思是,

我有一个模型:

class MyModel(models.Model):
...

def pre_save_model(sender, instance, **kwargs):
...

pre_save.connect(pre_save_model, sender=MyModel)

在代码的另一个地方我需要这样的东西:

a = MyModel()
...
disconnect_signals_for_model(a)
a.save()
...
reconnect_signals_for_model(a)

因为在这种情况下我需要保存模型而不执行函数 pre_save_model。

最佳答案

对于干净且可重用的解决方案,您可以使用上下文管理器:

class temp_disconnect_signal():
""" Temporarily disconnect a model from a signal """
def __init__(self, signal, receiver, sender, dispatch_uid=None):
self.signal = signal
self.receiver = receiver
self.sender = sender
self.dispatch_uid = dispatch_uid

def __enter__(self):
self.signal.disconnect(
receiver=self.receiver,
sender=self.sender,
dispatch_uid=self.dispatch_uid,
weak=False
)

def __exit__(self, type, value, traceback):
self.signal.connect(
receiver=self.receiver,
sender=self.sender,
dispatch_uid=self.dispatch_uid,
weak=False
)

现在,您可以执行以下操作:

from django.db.models import signals

from your_app.signals import some_receiver_func
from your_app.models import SomeModel

...
kwargs = {
'signal': signals.post_save,
'receiver': some_receiver_func,
'sender': SomeModel,
'dispatch_uid': "optional_uid"
}
with temp_disconnect_signal(**kwargs):
SomeModel.objects.create(
name='Woohoo',
slug='look_mom_no_signals',
)

注意:如果您的信号处理程序使用 dispatch_uid,您必须使用 dispatch_uid arg。 p>

关于django - 断开模型的信号并在 django 中重新连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2209159/

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