当在 Django 模型( .save()
)上执行更新/创建时,我希望能够“介入”并将某些特定属性与之前设置的属性进行比较(如果它们之前存在的话)。
我在想预存 信号 ,查找原始模型并执行 .objects.get(instance.id)
,但感觉很浪费。另外,验证是否已经发生在 pre_save()
?
最佳答案
关于 model validation :
Note that full_clean() will not be called automatically when you call your model’s save() method
然后,关于
pre-save signal
,请注意,您将保存的实例作为参数与消息一起发送。由于您的模型的前一个版本仅存在于数据库中,我看不出您还能从何处获得属性的先前值...您不知道为什么要这样做,因此很难说,但是我现在正在考虑其他解决方案:
* defining a custom signal that is sent everytime the attributes you are interested in are modified... This signal would then send two arguments : new value, old value
* perform the check directly when setting the attributes
如果您提供更多详细信息,可能会更容易...
编辑:
没错……如果您发出自定义的“foo_has_updated”,您将无法确定是否保存了修改。
在这种情况下,我想您可以在初始化实例时缓存您感兴趣的变量,并捕获后保存或预保存信号。
* With pre-save, you would be able to pre-process the data, but the saving operation might fail
* With post-save, you would be sure that the data has been saved.
缓存你的变量可以这样完成:
class CachedModel(models.Model):
cached_vars = [var1, var2, varN]
def __init__(self, *args, **kwargs):
super(CachedModel, self).__init__(*args, **kwargs)
self.var_cache = {}
for var in self.cached_vars:
self.var_cache[var] = copy.copy(getattr(self, var))
或者像这样......然后,在你的信号处理程序中:
def post_save_handler(sender, **kwargs):
instance = kwargs["instance"]
[(instance.var_cache[var], getattr(instance, var)) for var in instance.cached_var]
#[(<initial value>, <saved value>)
你得到了你需要的东西(我认为)!!!
关于Django:在更新模型之前,我想 "look at"它以前的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3216317/