识别 django post_save 信号中更改的字段 [英] Identify the changed fields in django post_save signal
问题描述
我正在使用 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
现在我想根据mode
字段的值是否改变来执行一个语句.
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/django 文档中的信号/#post-save 没有提到直接的方法.
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
来调试这个,发现instance
变量没有属性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.
推荐答案
将其设置在模型的 __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
现在您可以执行以下操作:
Now you can perform something like:
if instance.mode != instance.__original_mode:
# do something useful
这篇关于识别 django post_save 信号中更改的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!