gpt4 book ai didi

django - 不要在模型上发出后保存

转载 作者:行者123 更新时间:2023-12-02 02:24:52 26 4
gpt4 key购买 nike

我正在用 django 构建一个应用程序,我决定添加历史记录以跟踪模型中数据的更改。我正在使用 django-simple-history为达到这个。这个包显然在 post_save 信号上保存了一条历史记录。

我希望有时能够在不保存历史记录的情况下保存对象,例如当我运行一些后台查询并需要保存数据时。我的问题是,“我可以阻止模型发出保存后信号吗”

我目前有一个解决方法。我有一个 bool 变量,当我想显示该记录的历史记录时,我将其设置为 True。但这并不妨碍创造历史记录。

谢谢。

最佳答案

我对信号不太感兴趣,但我认为您应该更改信号处理程序,而不是停止发出信号。如果您在保存模型后需要做一些其他不相关的事情怎么办?

尝试在 django-simple-history/simple_history/models.py 中修补 create_historical_record(),将以下代码片段放在顶部:

create_historical_record(self, instance, type):
if hasattr(instance, 'save_history') and not instance.save_history:
return
#rest of method

您也可以尝试暂时断开历史跟踪器与您的模型实例的连接,然后再重新连接,但我不确定您会在哪里这样做。它也可能更容易出错。

哦,是的,您还可以将 HistoricalRecords 子类化:

class OptHistoricalRecords(HistoricalRecords):
def create_historical_record(self, instance, type):
if hasattr(instance, 'save_history') and not instance.save_history:
return
else:
super(OptHistoricalRecords,self).create_historical_record(instance,type)

关于django - 不要在模型上发出后保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6405131/

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