Django-simple-history正在每次保存目标模型时插入新记录。在docs中描述了F表达式的问题。我尝试使用覆盖的保存方法来规避此问题。
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
# some other actions
self.refresh_from_db()
但是似乎这不起作用。在调用post_save
之后是否直接调用基本模型的super().save()
信号?如果是这样,是否有办法解决此问题,将F表达式保留在目标模型中?]
更新:已保存的实例具有使用F表达式定义的属性之一,因此在其他模块中调用此代码:
instance.some_attribute = (F('some_attribute') + 15)
instance.save(update_fields=['some_attribute'])
[django-simple-history尝试将post_save
的扩展副本插入历史记录表时,在django-simple-history的instance
信号中引发错误。我试图刷新覆盖的save
方法中的实例,以摆脱some_attribute
中的F表达式,以便加载实际值。从回溯来看,post_save
似乎在super().save()
调用之后,刷新之前被调用。这是带有覆盖保存功能的Django post_save工作方式吗?如果是这样,有没有办法不更改更新代码(用F表达式保留更新)并解决历史记录在模型保存中的插入问题?
django-simple-history
提供创建历史记录之前和之后的信号:https://django-simple-history.readthedocs.io/en/2.7.0/signals.html
我建议使用这些方法在实例保存到历史表之前对其进行更新。这样的事情应该起作用:
from django.dispatch import receiver
from simple_history.signals import (
pre_create_historical_record,
post_create_historical_record
)
@receiver(pre_create_historical_record)
def pre_create_historical_record_callback(sender, **kwargs):
instance = kwargs["instance"]
if isinstance(instance, ModelYouWantToRefresh)
instance.refresh_from_db()