问题
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