Menu Close

How to check if a field has changed when saving with Python Django?

To check if a field has changed when saving with Python Django, we can override the `init method of the model class to keep a copt of the original value.

For instance, we write

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:
            super().save(force_insert, force_update, *args, **kwargs)
            self.__original_name = self.name

to add the __init__ method that sets the __original_name variable to self.name to keep the original name value.

And then in the if block in save, we check self.name to see if it’s different from self.__original_name to see if it’s saved with a new value.

Posted in Python, Python Answers