5

我正在使用 django 信号进行数据非规范化。这是我的代码:

# 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()被调用了两次。我认为我的代码中存在错误,但通过管理界面保存会得到相同的结果。

文档说了一些关于使用dispatch_uid来防止重复调用的内容,但我不明白是否是这种情况。如何使用dispatch_uid?我试过这个,但没有运气:

@receiver(pre_save, sender=Vote, dispatch_uid="my_unique_identifier")

任何想法为什么函数被调用两次以及如何避免它?

4

1 回答 1

9

很抱歉,造成混乱,但毕竟dispatch_uid解决了问题。请记住,您可能需要重新启动开发服务器才能看到效果,然后再提出关于 SO 的问题 :)

于 2011-04-26T07:49:34.843 回答