How to determine if a field has changed in a Django modelform

限于喜欢 提交于 2019-12-19 06:26:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!