Django: How to access original (unmodified) instance in post_save signal

后端 未结 3 2060
一生所求
一生所求 2020-12-13 00:21

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):
    \"\         


        
相关标签:
3条回答
  • 2020-12-13 00:35

    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.

    0 讨论(0)
  • 2020-12-13 00:56

    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 
    
    0 讨论(0)
  • 2020-12-13 00:56

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

    0 讨论(0)
提交回复
热议问题