django - 保存前比较旧的和新的字段值 [英] django - comparing old and new field value before saving

查看:423
本文介绍了django - 保存前比较旧的和新的字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django模型,我需要比较旧的和新的值保存前的值。



我尝试过save()的继承,并且pre_save信号。它被正确触发,但是找不到实际更改字段的列表,无法比较旧值和新值。有办法吗我需要它来优化预设动作。



谢谢!

解决方案

p>有一个非常简单的django方式来执行。



记住模型init中的值,如下所示:



$ _ code def __init __(self,* args,** kwargs):
super(MyClass,self).__ init __(* args,** kwargs)
self .initial_parametername = self.parametername
---
self.initial_parameternameX = self.parameternameX

现实生活中的例子:



在上课时:

  def __init __(self,* args,** kwargs):
super(MyClass,self).__ init __(* args,** kwargs)
self .__ important_fields = ['target_type','target_id' $ object_object','number','chain','expiration_date']
for self .__ important_fields:
setattr(self,'__original_%s'%field,getattr(self,field))

def has_changed(self):
对于自己的字段.__ important_fields:
orig ='__original_%s'%field
if getattr(self,orig)!= getattr(self,field):
return True
返回False

然后在模型保存方法中:



$ save $($)

$ b obj = super(MyClassForm,self)$ $ $ $ $ $ $ $ $ $ $ $ $ $))))))))))))))))))))))))))))) .save(commit = False)

如果obj.has_changed():

#如果我们用承诺失败,保存这个狗屎
如果提交:
obj.save(force_insert = True)

return obj


I have a django model, and I need to compare old and new values of field BEFORE saving.

I've tried the save() inheritence, and pre_save signal. It was triggered correctly, but I can't find the list of actualy changed fields and can't compare old and new values. There is a way? I need it for optimization of presave actions.

Thank you!

解决方案

There is very simple django way for doing it.

"Memorise" the values in model init like this:

def __init__(self, *args, **kwargs):
    super(MyClass, self).__init__(*args, **kwargs)
    self.initial_parametername = self.parametername
    ---
    self.initial_parameternameX = self.parameternameX

Real life example:

At class:

def __init__(self, *args, **kwargs):
    super(MyClass, self).__init__(*args, **kwargs)
    self.__important_fields = ['target_type', 'target_id', 'target_object', 'number', 'chain', 'expiration_date']
    for field in self.__important_fields:
        setattr(self, '__original_%s' % field, getattr(self, field))

def has_changed(self):
    for field in self.__important_fields:
        orig = '__original_%s' % field
        if getattr(self, orig) != getattr(self, field):
            return True
    return False

And then in modelform save method:

def save(self, force_insert=False, force_update=False, commit=True):
    # Prep the data
    obj = super(MyClassForm, self).save(commit=False)

    if obj.has_changed():

        # If we're down with commitment, save this shit
        if commit:
            obj.save(force_insert=True)

    return obj

这篇关于django - 保存前比较旧的和新的字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆