#Save on objects update?

6 messages · Page 1 of 1 (latest)

ionic pine
#

I have rewrite the save() method of some models of my app, and I found mymodel.objects.update() seems not triggering the rewritten save method of my model.
I am little confused what is the cleaner way / more pythonic way to address this problem
Should I:

  1. always call save() after objects.update() manually ( looks bad when update on filtered queryset huh
  2. write a manager mixin and call save() in objects.update() and replace the objects of all the mymodels that I rewrote the save() method (acceptable but not that good considering I have rewrote some managers of models
    3.Any better way to do it?🥺
charred temple
#

save and update are indeed different things—save will save a single object to the database, update runs an UPDATE SQL query across a queryset, and won't run any individual save methods—you can't do any per-object Python in that case. What is it you're adding to your save method that you need doing per-object?

hidden latch
#

If you need the .save(), it is preferable to avoid .update() and just loop over your queryset and call .save() individually. Maybe wrap the loop in a transaction if partial failure should rollback.

If you need the performance gains of an .update(), you may have to replicate the logic within your .save() in a way that you can apply it to a QuerySet in a more performant way.

ionic pine
charred temple
#

If you're only updating a single object, then yes you should use save instead of update, particularly when you have logic in save you want called

#

For bulk updates you will need to stop using update and iterate over each object calling save manually, or change your sync logic to run at an alternative point (like periodically for all objects or something)