在post_save信号中获取字段的先前值 [英] Get previous value of a field in post_save signal
问题描述
我在Django中有一个发布信号,我需要在其中访问字段的先前值:
I have a post signal in django, where I need to access previous value of a field:
post_save.connect(callback_function_postsave, sender=Media)
我理想地知道我应该为此使用pre_save:
I know ideally I should use pre_save for this:
pre_save.connect(callback_function_presave, sender=Media)
def callback_function_presave(sender, instance,*args,**kwargs):
try:
old_value = sender.objects.get(pk=instance.pk).field
except sender.DoesNotExist:
return
但是,必须在 post_signal
中获取 old_value
,因为基于此,我必须决定是否进行第3方api调用.我无法在 pre_save
中进行api调用,因为api使用的是同一数据库,并且期望提交更新的值.
However, its imperative to get the old_value
in post_signal
, because based on it, I have to decide whether to make a 3rd party api call or not. I cant make the api call in pre_save
as the api is using the same database and expects updated value committed.
我想到的一种可能的方法是将old_value添加到实例本身,然后可以通过post_save进行访问:
One possible way I can think of is add the old_value to instance itself which can then be accessed by post_save:
def callback_function_presave(sender, instance,*args,**kwargs):
try:
instance.old_value = sender.objects.get(pk=instance.pk).field
except sender.DoesNotExist:
return
def callback_function_postsave(sender, instance,*args,**kwargs):
try:
old_value = instance.old_value
except:
print "This is a new entry"
有没有更好的方法来实现这一目标.
Is there any better way to achieve this.
推荐答案
Unfortunately the post_save signal doesn't give you the old values (post_save). So storing the old value on the model seems to be a good solution.
我会这样写pre_save:
I would have written the pre_save like this:
def save_old_value(sender, instance, *args, **kwargs):
if instance.id:
instance.old_value = instance.__class__.objects.get(id=instance.id).old_value
这篇关于在post_save信号中获取字段的先前值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!