区分 signal.instance , Django/signals 中哪个字段发生了变化

Distinguish which field has changed in signal.instance , Django/signals

假设我有一个名为 BookModel 的模型,其中包含 4 个字段:(标题、作者、价格,publish_year)。

我在信号中有一个处理程序:

@receiver([post_save, post_delete], sender=BookModel)
def signal_handler(sender, instance, **kwargs):
…..

问题是如何区分特定模型字段在 save() 期间发生变化的情况。例如,如果价格发生变化,我想做些事情。最好用伪代码解释...

@receiver([post_save, post_delete], sender=BookModel)
def signal_handler(sender, instance, **kwargs):
# pseudo code bellow
if field “price” has changed:
    do stuff
else:
    do nothing

根据文档,如果我在 save() 中使用“update_fields”——这是可能的,但如果我不使用它呢???

当我从 post_save 或 post_delete 收到信号时仍然使用 1 个处理程序时,是否也可以区分这种情况?

@receiver([post_save, post_delete], sender=BookModel)
def signal_handler(sender, instance, **kwargs):
# pseudo code bellow
if signal is post_save:
    if field “price” has changed:
        do stuff
    else:
        do nothing
else:
    do other stuff

谢谢

您可以尝试 django-model-utils 的 FieldTracker 来跟踪模型字段中的变化。它还与 post_save 信号一起使用。

Checking changes using signals

The field tracker methods may also be used in pre_save and post_save signal handlers to identify field changes on model save.