9

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()
saeed foroughi
  • 1,662
  • 1
  • 13
  • 25
Tiancheng Liu
  • 782
  • 2
  • 9
  • 22

1 Answers1

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'
JPG
  • 82,442
  • 19
  • 127
  • 206
  • 3
    Also keep in mind, if object saved first time, it's old version isn't presented in database, so `objects.get` will cause exception. – Vladimir Chub Aug 30 '19 at 06:22
  • @zen11625 Thanks for the info. I've updated the answer to handling that situation – JPG Aug 30 '19 at 06:46