Model.save() not called on update()

半腔热情 提交于 2020-01-05 07:20:07

问题


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)

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')

How can I trigger this update on any change on any object of the Order class?


回答1:


According to the documentation here:

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()

so this will work:

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


来源:https://stackoverflow.com/questions/39915123/model-save-not-called-on-update

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