Django pre_save 触发两次

发布于 2024-11-02 20:50:18 字数 972 浏览 0 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

弥繁 2024-11-09 20:50:18

很抱歉,造成了混乱,但毕竟 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 :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文