1

The question is straight forward:

Is there a way to check whether any fields of an instance have been modified in model.save() method? Or maybe other method, .clean()?

The point is that you cannot explicitly name the fields to do the checking.

Is there any easy way to do it?

Jerry Meng
  • 1,466
  • 3
  • 21
  • 40
  • 1
    possible duplicate of [Django: When saving, how can you check if a field has changed?](http://stackoverflow.com/questions/1355150/django-when-saving-how-can-you-check-if-a-field-has-changed) – rnevius May 09 '14 at 15:35

1 Answers1

2

Way to get all field names:

[field.name for field in MODEL._meta.fields]

Way to check field value by fields name as string:

getattr(obj, field_name)

so you can modify this Django: When saving, how can you check if a field has changed? answer like this:

def save(self, *args, **kw):
    if self.pk is not None:
        orig = MyModel.objects.get(pk=self.pk)
        field_names = [field.name for field in MyModel._meta.fields]
        fields_stats = {}
        for field_name in field_names:
            fields_stats[field_name] = getattr(orig, field_name) != getattr(self, field_name)
    super(MyModel, self).save(*args, **kw)

dictionary field_stats will be like

{
    'field_name1': True,
    'field_name1': False,
}

Where True means field has changed, and False mean field hasn't changed

Community
  • 1
  • 1
Dmitry Loparev
  • 462
  • 2
  • 9
  • Thanks for the help, but actually the marked answer in that link is not my first choice. I think the answer about ModelDiffMixin is more promising. – Jerry Meng May 09 '14 at 17:30