未在update()上调用Model.save() [英] Model.save() not called on update()

查看:47
本文介绍了未在update()上调用Model.save()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Model 模型中添加了 save()方法,以更新一些时间戳:

I added a save() method to my Model, to update some timestamps:

class Order(models.Model):
   deliveredtime = models.DateTimeField(blank=True, null=True, default=None)
   status = models.CharField(default='NEW', max_length=20)

   def save(self, *args, **kw):
        if self.status == "DELIVERED" and self.deliveredtime is None:
            self.deliveredtime = timezone.now()

        super(Order, self).save(*args, **kw)

但是我发现调用 update 在对象列表上:

But I found out this method is not called when calling update on a list of objects:

Order.objects.filter(status='WAITING FOR DELIVERY').update(status='DELIVERED')

如何在<$ c的任何对象上进行任何更改时触发此更新$ c>订单类?

推荐答案

根据文档此处


最后,意识到该update()在SQL级别进行更新,因此不会在模型上调用任何save()方法,也不会发出pre_save或post_save信号(这是调用Model.save()的结果)。如果要为具有自定义save()方法的模型更新一堆记录,请遍历它们并调用save()

Finally, realize that update() does an update at the SQL level and, thus, does not call any save() methods on your models, nor does it emit the pre_save or post_save signals (which are a consequence of calling Model.save()). If you want to update a bunch of records for a model that has a custom save() method, loop over them and call save()

因此这将起作用:

for order in Order.objects.filter(status='WAITING FOR DELIVERY'):
    order.status = 'DELIVERED'
    order.save()

这篇关于未在update()上调用Model.save()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆