0

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 )?

George
  • 37
  • 9
  • An attribute with a double-underscore is name-mangled so it is not directly accessible from outside the class. Solution is not to use a double underscore but a single one (or none at all). – Daniel Roseman Dec 09 '18 at 13:55
  • @DanielRoseman Thank you! I tried to do with a single underscore, but pycharm gave a warning "Access to a protected member _folder of a class" – George Dec 09 '18 at 14:00

1 Answers1

0

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

jackotonye
  • 3,537
  • 23
  • 31