简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM