[英]Django pre_save triggered twice
I am using django signals for data denormalization. 我正在使用django信号进行数据非规范化。 Here is my code:
这是我的代码:
# 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()
I cannot understand why, but when my Vote
instance is being saved, update_post_votes_on_save()
is being called twice. 我无法理解为什么,但是当我的
Vote
实例被保存时, update_post_votes_on_save()
被调用两次。 I thought there was a bug in my code, but saving through admin interface gives the same result. 我认为我的代码中存在一个错误,但通过管理界面保存会产生相同的结果。
Docs say something about using dispatch_uid
to prevent duplicate calls , but I cannot understand if this is the case. 文档说了一些关于使用
dispatch_uid
来防止重复调用的事情,但我不明白是否是这种情况。 How to use dispatch_uid
? 如何使用
dispatch_uid
? I've tried this, but with no luck: 我试过这个,但没有运气:
@receiver(pre_save, sender=Vote, dispatch_uid="my_unique_identifier")
Any ideas why function is being called twice and how to avoid it? 任何想法为什么函数被调用两次以及如何避免它?
I'm sorry, for the confusement, but dispatch_uid
solved the problem, after all. 对不起,对于娱乐,但是
dispatch_uid
毕竟解决了这个问题。 Just remember, that you might have to restart the development server to see the effect, before asking a question on SO :) 请记住,您可能需要重新启动开发服务器才能看到效果,然后再询问SO :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.