Django:将变量从pre_save传递到post_save信号

jva*_*ooy 6 django django-signals

我使用pre_save和post_save信号将分析发送到Mixpanel.我更喜欢将它与我的模型的保存方法分开.

有没有办法在pre_save信号出现时保存实例的旧值,然后在post_save上检查新值?

我的代码看起来像这样:

@receiver(pre_save, sender=Activity)
def send_user_profile_analytics(sender, **kwargs):
    activity_completed_old_value = kwargs['instance'].is_completed
    # store this value somewhere?

@receiver(post_save, sender=Activity)
def send_user_profile_analytics(sender, **kwargs):
    if kwargs['instance'].is_completed != activity_completed_old_value:
        # send analytics
Run Code Online (Sandbox Code Playgroud)

对我来说,使用post_save发送分析而不是pre_save似乎更健壮,但在那时我无法看到模型实例中发生了什么变化.我想在我的模型的保存功能中阻止使用全局变量或实现某些东西.

Don*_*Don 7

您可以将它们存储为实例属性.

@receiver(pre_save, sender=Activity)
def send_user_profile_analytics(sender, **kwargs):
    instance = kwargs['instance']
    instance._activity_completed_old_value = instance.is_completed

@receiver(post_save, sender=Activity)
def send_user_profile_analytics(sender, **kwargs):
    instance = kwargs['instance']     
    if instance.is_completed != instance._activity_completed_old_value:
        # send analytics
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您只能在is_completed发生变化时"发送分析" save(这意味着save不只是存储值,而是进行进一步的详细说明).

如果要在实例生命周期(即从创建到生成时save)更改字段时执行操作,则应在post_init(而不是pre_save)期间存储初始值.

  • 我试过这个,但是当我尝试保存模型时,当我处于“post_save”时,“Activity”实例没有“_activity_completed_old_value” (2认同)