我如何检查 post_save 中的模型字段是否已更改?

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

如果其中一个模型字段已更新,我必须在 post_save 中执行一些额外的逻辑,但无法检查它是否已更新。

试图像这样覆盖 init 方法

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

并在 post_save 中检查

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

但出现异常

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

我做错了什么(除了使用信号 :D )?

那是因为你使用的名字改写了。

双下划线(名称修改)

来自 Python 文档:

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.

也就是说访问instance.__old_city你需要使用_className__attribute_name

所以__old_city会被破坏->_Profile__old_city