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

后端 未结 4 1353
甜味超标
甜味超标 2021-01-04 07:25

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?

相关标签:
4条回答
  • 2021-01-04 07:47

    It seems that you have reinvented .has_changed() method.

    0 讨论(0)
  • 2021-01-04 07:51

    Form contains a property changed_data which holds a list of all the fields whose values have changed.

    Try:

    'fieldname' in myforminstance.changed_data
    
    0 讨论(0)
  • 2021-01-04 07:59

    Extending on Airs's answer, for multiple fields:

    In a scenario where you'd like to track changes for a list of fields ['field_a', 'field_b', 'field_c']


    If you'd like to check if any of those fields has changed:

    any(x in myforminstance.changed_data for x in ['field_a', 'field_b', 'field_c'])
    

    If you'd like to check if all of those fields have changed:

    all(x in myforminstance.changed_data for x in ['field_a', 'field_b', 'field_c'])
    
    0 讨论(0)
  • 2021-01-04 08:02

    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...
    
    0 讨论(0)
提交回复
热议问题