[英]Detect field change using post_save instead of pre_save signal
I need to do some actions when one field has changed. 当一个字段更改时,我需要执行一些操作。
Since this action needs to work with already saved object, I can't use pre_save
signal like this: 由于此操作需要处理已保存的对象,因此无法使用
pre_save
信号,如下所示:
@receiver(pre_save, sender=reservation_models.Reservation)
def generate_possible_pairs(sender, instance, **kwargs):
try:
reservation_old = sender.objects.get(pk=instance.pk)
except sender.DoesNotExist:
pass # Object is new, so field hasn't technically changed, but you may want to do something else here.
else:
if not reservation_old.datetime == instance.datetime: # Field has changed
do_something(instance) # It would be better to be sure instance has been saved
Is it possible to use post_save
signal for this? 是否可以为此使用
post_save
信号?
I would like to avoid adding temporary attributes to this model. 我想避免向此模型添加临时属性。
Using the post_save signal you won't be able to retrieve the previous state from db - But why use a signal at all ? 使用post_save信号,您将无法从db检索以前的状态-但是为什么要使用信号呢?
class Reservation(models.Model):
def save(self, *args, **kw):
old = type(self).objects.get(pk=self.pk) if self.pk else None
super(Reservation, self).save(*args, **kw)
if old and old.datetime != self.datetime: # Field has changed
do_something(self)
You may also want to read this : https://lincolnloop.com/blog/django-anti-patterns-signals/ 您可能还需要阅读以下内容: https : //lincolnloop.com/blog/django-anti-patterns-signals/
Yes you can use a post_save too. 是的,您也可以使用post_save。 You should however remember signals are synchronous
但是,您应该记住信号是同步的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.