Django .update doesn't call override save?

假装没事ソ 提交于 2020-07-07 05:20:26

问题


I am trying to call this overrride save method in models:

def save(self, *args, **kwargs):
    if self.done is True:
        if self.averagepa is None:
            pass
        elif self.averagepa < 26:
            self.links = 5
        elif self.averagepa < 31:
            self.links = 10
        elif self.averagepa < 36:
            self.links = 15
        elif self.averagepa < 41:
            self.links = 20
        else:
            self.links = 99
super(KW, self).save(*args, **kwargs)

This works perfectly if I just save model in admin panel. But when I try to update it via ./manage.py shell like this:

KW.objects.filter(id=138).update()

It doesn't trigger it. How can I call save override method with update from shell?


回答1:


This is the documented behaviour of the update() method.

Be aware that the update() method is converted directly to an SQL statement. It is a bulk operation for direct updates. It doesn’t run any save() methods on your models, or emit the pre_save or post_save signals (which are a consequence of calling save()), or honor the auto_now field option. If you want to save every item in a QuerySet and make sure that the save() method is called on each instance, you don’t need any special function to handle that. Just loop over them and call save().

In your case:

kw = KW.objects.get(id=138)
# update kw
kw.save()


来源:https://stackoverflow.com/questions/33809060/django-update-doesnt-call-override-save

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