4
我正在使用django信號進行數據非規範化。這裏是我的代碼:Django pre_save被觸發兩次
# 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()
被稱爲兩次。我認爲我的代碼中存在一個錯誤,但通過管理界面保存會得到相同的結果。
文檔說一些關於using dispatch_uid
to prevent duplicate calls,但我不明白,如果是這樣的話。如何使用dispatch_uid
?我已經試過這一點,但沒有運氣:
@receiver(pre_save, sender=Vote, dispatch_uid="my_unique_identifier")
任何想法,爲什麼函數被調用兩次,如何避免呢?
在您的代碼庫中搜索註冊信號的位置 - 確保它沒有註冊兩次 – Chris 2011-04-19 14:55:02
@chris :dispatch_uid應該防止它被註冊兩次。 @ silver-light:你是如何驗證你的處理程序被調用兩次的? – shadfc 2011-04-19 15:23:57
請查看http://groups.google.com/group/django-users/browse_thread/thread/0f8db267a1fb036f也許您也有重複的註冊。 – fceruti 2011-04-19 16:13:21