Skip to content Skip to sidebar Skip to footer

Django: How To Access Original (unmodified) Instance In Post_save Signal

I want to do a data denormalization for better performance, and put a sum of votes my blog post receives inside Post model: class Post(models.Model): ''' Blog entry ''' aut

Solution 1:

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.

Solution 2:

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 

Solution 3:

You can use the FieldTracker from django-model-utils: https://django-model-utils.readthedocs.io/en/latest/utilities.html#field-tracker

Post a Comment for "Django: How To Access Original (unmodified) Instance In Post_save Signal"