Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Imagine I have a model called A, which has a field called name. How can I get previous value and new value in pre_save signal?

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

Will the name be the old value or the new value when I call the following?

a = A.objects.create(name="John")
a.name = "Lee"
a.save()
like image 275
Tiancheng Liu Avatar asked Aug 09 '18 20:08

Tiancheng Liu


1 Answers

From the doc instance The actual instance being saved.

You will get the old instance of A by explicitly calling it using .get() method as,

@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'
like image 198
JPG Avatar answered Nov 15 '22 04:11

JPG