37

我正在尝试设置一些类似于以下内容的 post_save 接收器

@receiver(post_save, sender=Game, dispatch_uid='game_updated')
def game_updated(sender, **kwargs):

    '''DO SOME STUFF HERE'''

    MyPick.objects.filter(week=game.week, team=game.home_team).update(result=home_result)
    MyPick.objects.filter(week=game.week, team=game.away_team).update(result=away_result)


@receiver(post_save, sender=MyPick, dispatch_uid='user_pick_updated')
def update_standings(sender, **kwargs):
    '''DO STUFF'''

在更新 Game 对象后,第一个接收器被正确调用,但是对 MyPick 对象的更新调用不会导致调用第二个接收器。post_save 信号在更新时不起作用还是我在这里遗漏了其他东西?

谢谢

4

2 回答 2

67

update()直接转换成SQL语句;它不会调用save()模型实例,因此不会发出pre_saveandpost_save信号。如果您希望调用信号接收器,则应遍历查询集,并为每个模型实例进行更改并调用save()自己。

于 2011-09-11T05:32:34.330 回答
41

@Ismali Badawi 的回答还有一件事。


这叫_ post_save

user = User.objects.get(id=1) 
user.username='edited_username' 
user.save()

不叫 post_save

User.objects.filter(id=1).update(username='edited_username')

在代码中,

from django.db.models.signals import post_save

@receiver(post_save, sender=User)
def do_something_when_user_updated(sender, instance, created, **kwargs):
    if not created:
        # User object updated
        user_obj = instance
        pass
于 2016-02-06T08:08:19.793 回答