To do this in a more abstract way, see the documentation for the model method from_db(), which is called when loading data into the model instance from the database. With this method, you can cache the original value of a field when it is loaded, and then compare it with the current value in the method save().
Example (note, I did not check this code):
class SaveIfModified(models.Model):
foo = models.TextField()
@classmethod
def from_db(cls, db, field_names, values):
instance = super()
if "foo" in field_names:
instance._foo = values[field_names.index("foo")]
return instance
def save(self, *args, **kwargs):
if self.foo == self._foo:
return
super().save(*args, **kwargs)
source
share