如何确定Django模型形式中的字段是否已更改 [英] How to determine if a field has changed in a Django modelform
本文介绍了如何确定Django模型形式中的字段是否已更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很惊讶这很难做到。但是我想到了这一点,这似乎至少对我的简单案例有用。有人可以推荐一种更好的方法吗?
I was surprised that this was difficult to do. However I came up with this, which seems to work at least for my simple case. Can anyone recommend a better approach?
def field_changed(self, fieldname):
"""Tests if the value of the field changed from the original data"""
orig_value = self.fields[fieldname].initial or getattr(self.instance, field, None)
orig_value = getattr(orig_value, 'pk', orig_value)
if type(orig_value) is bool:
# because None and False can be interchangeable
return bool(self.data.get(fieldname)) != bool(orig_value)
else:
return unicode(self.data.get(fieldname)) != unicode(orig_value)
推荐答案
表单包含一个属性changed_data,该属性包含其值已更改的所有字段的列表。
Form contains a property changed_data which holds a list of all the fields whose values have changed.
尝试:
'fieldname' in myforminstance.changed_data
这篇关于如何确定Django模型形式中的字段是否已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文