识别django post_save信号中已更改的字段 [英] Identify the changed fields in django post_save signal

查看:486
本文介绍了识别django post_save信号中已更改的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用django的post_save信号在保存模型后执行一些语句。

I'm using django's post_save signal to execute some statements after saving the model.

class Mode(models.Model):
    name = models.CharField(max_length=5)
    mode = models.BooleanField()


from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Mode)
def post_save(sender, instance, created, **kwargs):
        # do some stuff
        pass

现在我要执行一个语句, code> mode field has changed or not。

Now I want to execute a statement based on whether the value of the mode field has changed or not.

@receiver(post_save, sender=Mode)
def post_save(sender, instance, created, **kwargs):
        # if value of `mode` has changed:
        #  then do this
        # else:
        #  do that
        pass

我看了几个SOF线程和一个博客但是找不到解决方案他的。所有这些都试图使用pre_save方法或形式,这不是我的用例。 https://docs.djangoproject.com/es/1.9/ref / signals /#post-save 在django文档中没有提到直接的方式来做到这一点。

I looked at a few SOF threads and a blog but couldn't find a solution to this. All of them were trying to use the pre_save method or form which are not my use case. https://docs.djangoproject.com/es/1.9/ref/signals/#post-save in the django docs doesn't mention a direct way to do this.

下面的链接中的一个答案看起来很有前途,我不知道如何使用它。我不知道最新的django版本是否支持,因为我使用 ipdb 来调试,发现实例变量没有属性 has_changed ,如下面的答案所述。

An answer in the link below looks promising but I don't know how to use it. I'm not sure if the latest django version supports it or not, because I used ipdb to debug this and found that the instance variable has no attribute has_changed as mentioned in the below answer.

Django:保存时,如何检查字段已更改?

推荐答案

设置在 __ init __ 你的模型,所以你可以访问它。

Set it up on the __init__ of your model so you'll have access to it.

def __init__(self, *args, **kwargs):
    super(YourModel, self).__init__(*args, **kwargs)
    self.__original_mode = self.mode

现在你可以执行类似:

if instance.mode != instance.__original_mode:
    # do something useful

这篇关于识别django post_save信号中已更改的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆