How do I get old value and new value in pre_save function in Django?
Asked Answered
D

1

10

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()
Demagogic answered 9/8, 2018 at 20:46 Comment(0)
C
21

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'
Cockchafer answered 10/8, 2018 at 5:25 Comment(2)
Also keep in mind, if object saved first time, it's old version isn't presented in database, so objects.get will cause exception.Overlying
@zen11625 Thanks for the info. I've updated the answer to handling that situationCockchafer

© 2022 - 2024 — McMap. All rights reserved.