Search code examples
pythondjangodjango-signals

How can i check if model field was changed in post_save?


I have to do some extra logic in post_save if one of model fields was updated, but can't check if it was updated.

Tried to override init method like this

def __init__(self, *args, **kwargs):
    super(Profile, self).__init__(*args, **kwargs)
    self.__old_city = self.city

and in post_save check

if instance.city != instance.__old_city:
    #extra logic

but got an exception

AttributeError: 'Profile' object has no attribute '__old_city'

What i'm doing wrong(except of using signals :D )?


Solution

  • Thats because your using name mangling.

    Double Underscore (Name Mangling)

    From the Python docs:

    Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.

    Which means to access instance.__old_city you need to use _className__attribute_name

    So __old_city will be mangled -> _Profile__old_city