使用post_save而不是pre_save信号检测字段更改

时间:2017-08-01 11:47:47

标签: python django django-models django-signals django-database

当一个字段发生变化时,我需要做一些动作。

由于此操作需要使用已保存的对象,因此我无法使用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

是否可以使用post_save信号?

我想避免为此模型添加临时属性。

2 个答案:

答案 0 :(得分:5)

使用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)

您可能还想阅读此内容:https://lincolnloop.com/blog/django-anti-patterns-signals/

答案 1 :(得分:-2)

是的,你也可以使用post_save。但是你应该记住信号是同步的