[Answered ]-Django model.save(): Check if ANYTHING changed

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

Leave a comment