Django: How to access original (unmodified) instance in post_save signal
I believe post_save
is too late to retrieve the unmodified version. As the name implies the data has already been written to the db at that point. You should use pre_save
instead. In that case you can retrieve the model from the db via pk: old = Vote.objects.get(pk=instance.pk)
and check for differences in the current instance and the previous instance.
This is not an optimal solution, but it works.
@receiver(pre_save, sender=SomeModel)
def model_pre_save(sender, instance, **kwargs):
try:
instance._pre_save_instance = SomeModel.objects.get(pk=instance.pk)
except SomeModel.DoesNotExist:
instance._pre_save_instance = instance
@receiver(signal=post_save, sender=SomeModel)
def model_post_save(sender, instance, created, **kwargs):
pre_save_instance = instance._pre_save_instance
post_save_instance = instance
You can use the FieldTracker from django-model-utils: https://django-model-utils.readthedocs.io/en/latest/utilities.html#field-tracker