问题
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 anysave()
methods on your models, or emit the pre_save or post_save signals (which are a consequence of callingsave()
), or honor the auto_now field option. If you want to save every item in a QuerySet and make sure that thesave()
method is called on each instance, you don’t need any special function to handle that. Just loop over them and callsave()
.
In your case:
kw = KW.objects.get(id=138)
# update kw
kw.save()
来源:https://stackoverflow.com/questions/33809060/django-update-doesnt-call-override-save