django 如何在 pre_save 函数中获取旧值和新值

django how to get old value and new value in pre_save fucntion

假设我有一个名为 A 的模型,它有一个名为 name 的字段。如何获得 pre_save 信号中的先前值和新值?

@receiver(pre_save, sender=A)
def signal_product_manage_latest_version_id(
        sender, instance, update_fields=None, **kwargs):
    if 'name' in update_fields:
        print(instance.name)

下面调用时name是旧值还是新值?

a = A.objects.create(name="John")
a.name = "Lee"
a.save()

来自docinstance实际实例正在保存

您将通过使用 .get()[=24 显式调用它来获得 Aold 实例 =] 方法为,

@receiver(pre_save, sender=A)
def signal_product_manage_latest_version_id(sender, instance, update_fields=None, **kwargs):
    try:
        old_instance = A.objects.get(id=instance.id)
    except A.DoesNotExist:  # to handle initial object creation
        return None  # just exiting from signal
    # your code to with 'old_instance'