问题
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)
回答1:
Form contains a property changed_data which holds a list of all the fields whose values have changed.
Try:
'fieldname' in myforminstance.changed_data
回答2:
It seems that you have reinvented .has_changed() method.
回答3:
You must override the method post_save
. Overriding methods is a good practice in Django: https://docs.djangoproject.com/en/dev/ref/signals/#post-save
I suggest you adding something like this into your model class:
def post_save(self, sender, instance, created, raw, using, update_fields):
if 'the_field' in update_fields:
# Do whatever...
来源:https://stackoverflow.com/questions/35879101/how-to-determine-if-a-field-has-changed-in-a-django-modelform