Django pre_save 触发两次
我正在使用 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")
任何想法为什么函数被调用两次以及如何避免它?
I am using django signals for data denormalization. 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. 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. How to use 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
很抱歉,造成了混乱,但毕竟
dispatch_uid
解决了问题。请记住,在提出有关 SO 的问题之前,您可能必须重新启动开发服务器才能看到效果:)I'm sorry, for the confusement, but
dispatch_uid
solved the problem, after all. Just remember, that you might have to restart the development server to see the effect, before asking a question on SO :)