我正在使用 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")
任何想法为什么函数被调用两次以及如何避免它?