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?