2017-10-10 21 views
0

私のモデルでカウントを更新するために実行しようとしているポスト保存機能があります。Djangoポスト保存機能が保存されない

投稿の保存の2つの方法を試しましたが、私の管理ページに保存した後、私のデータベース内の "5"にカウンタを更新していません。以下

# method for updating 
def update_tagpoll(sender, instance, *args, **kwargs): 
    # countptype = c.polltype.count() 
    # TagPoll.objects.count = countptype 
    instance.counter = 5 

post_save.connect(update_tagpoll, sender=TagPoll) 


# method for updating 
@receiver(post_save, sender=TagPoll, dispatch_uid="update_tagpoll_count") 
def update_tagpoll(sender, instance, **kwargs): 
    instance.counter == 5 

私も(予想される)最大の再帰の問題につながるinstance.save()を実行しようとしました

は、私は更新しようとしているモデルです。

class TagPoll(models.Model): 
    title = models.CharField(max_length=120, unique=True) 
    polltype = models.ManyToManyField(Ptype, blank=True) 
    active = models.BooleanField(default=True) 
    counter = models.IntegerField(default=0) 

    def __unicode__(self): 
     return str(self.title) 

どのような問題があるかわかりませんが、アドバイスをいただければ幸いです。あなたはinstance.counterかどうかを確認しようとする信号で

+1

'instance.counter == 5'は' instance.counter'を5に設定しません - それは5と等しいかどうかを確認します。また、モデルを変更している場合は、それは 'pre_save'フックで、' post_save'を取得するには遅すぎます。 – Shadow

答えて

1

は、あなたがそれゆえ、あなたがpre_save信号を使用する必要があり、再帰につながる5で追加または5

@receiver(post_save, sender=TagPoll, dispatch_uid="update_tagpoll_count") 
def update_tagpoll(sender, instance, **kwargs): 
    instance.counter = 5 
    # instance.counter += 5 if you want to increment it by 5. 
    instance.save() 

post_saveに変更する必要が5です。 IMO。

インスタンスを保存する直前にカウンタの値を変更するものがあります。

1
@receiver(pre_save, sender=TagPoll) 
def update_tagpoll(sender, instance, **kwargs): 
    instance.counter = 5