我使用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
对我来说,使用post_save来发送分析数据似乎比pre_save更为健壮,但是那时我看不到模型实例中发生了什么变化。我想防止在模型的保存功能中使用全局变量或实现某些操作。
您可以将它们存储为实例属性。
@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
这样,您仅在is_completed
期间发生变化时才“发送分析” save
(这意味着save
不仅存储了价值,而且进行了进一步的阐述)。
如果要在实例生存期内(即从创建到save
)更改字段时执行操作,则应在post_init
(而不是pre_save
)期间存储初始值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句