2017-10-10 230 views
0

我有后保存功能,我试图执行更新我的模型计数。Django后保存功能不保存

我试过这两种方法做后保存,他们都没有更新我的数据库内的“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) 

我似乎无法找到问题,任何意见将不胜感激。

+1

'instance.counter == 5'不会将'instance.counter'设置为5 - 它会检查它是否等于5.另外,如果您要修改模型,您可能需要做在'pre_save'钩子中,因为你得到'post_save'的时候已经太迟了...... – Shadow

回答

1

在你想检查instance.counter信号是5。你必须通过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会导致递归,因此你应该使用pre_save信号IMO。

哪些会在保存实例之前修改计数器的值。

@receiver(pre_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. 
1
@receiver(pre_save, sender=TagPoll) 
def update_tagpoll(sender, instance, **kwargs): 
    instance.counter = 5