Django .update不调用覆盖保存吗? [英] Django .update doesn't call override save?
问题描述
我正在尝试在模型中调用此方法:
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)
如果我只是将模型保存在管理面板中,这将非常有效。但是,当我尝试通过 ./ manage.py shell
对其进行更新时:
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?
推荐答案
这是 update()
请注意,
update()
方法直接转换为一个SQL语句。这是直接更新的批量操作。它不会在模型上运行任何save()
方法,也不会发出pre_save或post_save信号(这是调用save()的结果)
),或使用auto_now字段选项。如果要将每个项目保存在QuerySet中,并确保在每个实例上调用save()
方法,则不需要任何特殊函数来处理它。只需遍历它们并调用save()
。
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()
.
在您的情况下:
kw = KW.objects.get(id=138)
# update kw
kw.save()
这篇关于Django .update不调用覆盖保存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!