Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django pre_save triggered twice

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?

like image 296
Silver Light Avatar asked Apr 19 '11 14:04

Silver Light


1 Answers

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

like image 199
Silver Light Avatar answered Oct 19 '22 15:10

Silver Light