When saving, how can you check if a field has changed?

Essentially, you want to override the __init__ method of models.Model so that you keep a copy of the original value. This makes it so that you don’t have to do another DB lookup (which is always a good thing).

    class Person(models.Model):
        name = models.CharField()

        __original_name = None

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.__original_name = self.name

        def save(self, force_insert=False, force_update=False, *args, **kwargs):
            if self.name != self.__original_name:
                # name changed - do something here

            super().save(force_insert, force_update, *args, **kwargs)
            self.__original_name = self.name

Leave a Comment