Signals working only in shell,not working in admin and frontend

和自甴很熟 提交于 2019-12-25 07:58:30

问题


I am trying to assign some values to a model field after post-save.The model is

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()

As you can see,The signal is used to assign values to Authority fields after saving Feed model.This works in shell,as the fields are automatically updated but it doesnt work on creating or editing a feed instance in admin or front-end website.Though its print out the '-------' and '****' on execution in the console.Pls kindly help


回答1:


Need to do kwargs['instance'].auth.save() in order to write those changes to the related Authority to the database. If I had to guess, it looks like it's working in the shell because you're looking at the unsaved object in memory, while on your working site you're looking at the values returned from the database.



来源:https://stackoverflow.com/questions/39103632/signals-working-only-in-shell-not-working-in-admin-and-frontend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!