2016-08-23 12 views
0

我想一些值分配给后后save.The模型的模型场不工作是信号工作只能在外壳,在管理和前端

class Authority(models.Model): 
    no_of_feeds=models.PositiveIntegerField() 
    no_of_rf=models.PositiveIntegerField() 
    no_of_urf=models.PositiveIntegerField() 


class Feed(models.Model): 
     auth=models.ForeignKey(Authority,blank=False) 

    @receiver(post_save, sender = Feed) 
    def update_model_feed(sender, **kwargs): 
     if kwargs['created']: #only fire when creating new objects 
      kwargs['instance'].auth.no_of_feeds=kwargs['instance'].auth.feed_set.all().count() 
      kwargs['instance'].auth.no_of_rf=kwargs['instance'].auth.feed_set.filter(resolved=True).count() 
      kwargs['instance'].auth.no_of_urf=kwargs['instance'].auth.feed_set.filter(resolved=False).count() 
      print '******************************' 
     elif not kwargs['created']: 
      kwargs['instance'].auth.no_of_feeds=kwargs['instance'].auth.feed_set.all().count() 
      kwargs['instance'].auth.no_of_rf=kwargs['instance'].auth.feed_set.filter(resolved=True).count() 
      print '-------------------------------' 
      kwargs['instance'].auth.no_of_urf=kwargs['instance'].auth.feed_set.filter(resolved=False).count() 

正如你所看到的,该信号是用来在保存Feed模型后,将值分配给Authority字段。这在shell中工作,因为字段会自动更新,但它不适用于在管理员或前端网站中创建或编辑馈送实例。虽然它打印出'--- ----'和'****'在控制台上执行。请随时帮忙

回答

0

需要做kwargs['instance'].auth.save()为了写这些改变到相关的Authority到数据库。如果我不得不猜测,它看起来像在shell中工作,因为您正在查看内存中未保存的对象,而在工作站点上查看从数据库返回的值。

+0

这正是原因。它翻转了我的脑海,这是我第二次使用django-signals。非常感谢你 –

+0

随时,很高兴它的工作! – souldeux

+0

你能帮我回答这个问题吗?http://stackoverflow.com/questions/39183479/django-all-auth-form-errors-not-displaying谢谢。 –