2016-08-23 15 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謝謝。 –