4
我正在使用django信号进行数据非规范化。这里是我的代码:Django pre_save被触发两次
# vote was saved
@receiver(pre_save, sender=Vote)
def update_post_votes_on_save(sender, instance, **kwargs):
""" Update post rating """
# is vote is being updated, then we must remove previous value first
if instance.id:
old_vote = Vote.objects.get(pk=instance.id)
instance.post.rating -= old_vote.value
# now adding the new vote
instance.post.rating += instance.value
instance.post.save()
我不明白为什么,但被保存我的Vote
实例时,update_post_votes_on_save()
被称为两次。我认为我的代码中存在一个错误,但通过管理界面保存会得到相同的结果。
文档说一些关于using dispatch_uid
to prevent duplicate calls,但我不明白,如果是这样的话。如何使用dispatch_uid
?我已经试过这一点,但没有运气:
@receiver(pre_save, sender=Vote, dispatch_uid="my_unique_identifier")
任何想法,为什么函数被调用两次,如何避免呢?
在您的代码库中搜索注册信号的位置 - 确保它没有注册两次 – Chris 2011-04-19 14:55:02
@chris :dispatch_uid应该防止它被注册两次。 @ silver-light:你是如何验证你的处理程序被调用两次的? – shadfc 2011-04-19 15:23:57
请查看http://groups.google.com/group/django-users/browse_thread/thread/0f8db267a1fb036f也许您也有重复的注册。 – fceruti 2011-04-19 16:13:21