6

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?

joaquin
  • 82,968
  • 29
  • 138
  • 152
Silver Light
  • 44,202
  • 36
  • 123
  • 164
  • Search your codebase for where you are registering the signal - make sure it isn't registered twice – Chris Apr 19 '11 at 14:55
  • @chris: The dispatch_uid should prevent it from being registered twice. @silver-light: How have you verified that your handler is being called twice? – shadfc Apr 19 '11 at 15:23
  • Check this out http://groups.google.com/group/django-users/browse_thread/thread/0f8db267a1fb036f Maybe you have duplicate registration too. – fceruti Apr 19 '11 at 16:13
  • @shadfc, yes I did, using debugger in PyCharm – Silver Light Apr 19 '11 at 16:20

1 Answers1

9

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 :)

Silver Light
  • 44,202
  • 36
  • 123
  • 164