如何确定Django模型中的字段是否已更改

Pet*_*rth 7 django django-forms

我很惊讶这很难做到.但是我想出了这个,这似乎至少对我的简单案例起作用.有谁能推荐更好的方法?

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)
Run Code Online (Sandbox Code Playgroud)

Air*_*irs 19

表单包含一个属性changed_data,其中包含值已更改的所有字段的列表.

尝试:

'fieldname' in myforminstance.changed_data
Run Code Online (Sandbox Code Playgroud)

  • 技术说明:如果表单字段使用模型字段默认值呈现,该值之前未设置(例如在创建时),那么,除非更改默认值,否则该字段的名称将不会在 `changed_data` 列表中 (6认同)

alT*_*Tus 9

看来你已经重新发明了has_changed方法.

  • 否决“field.has_changed()”似乎需要 2 个必需的位置参数:“initial”和“data”。然后,这将需要检索原始表单数据和新表单数据,此时您不妨自己比较新旧条目。[Airs的答案](/sf/answers/3048514731/)更直接。 (3认同)