django post_save更新信号

时间:2011-09-11 02:06:48

标签: django django-signals

我正在尝试设置一些类似于以下

的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信号不能用于更新,还是我在这里遗漏了其他东西?

由于

2 个答案:

答案 0 :(得分:47)

update() is converted directly to an SQL statement;它不会在模型实例上调用save(),因此不会发出pre_savepost_save个信号。如果您希望调用信号接收器,则应该遍历查询集,并为每个模型实例进行更改并自己调用save()

答案 1 :(得分:15)

对于@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