Using QuerySet.update() versus ModelInstance.save() in Django

后端 未结 2 581
情深已故
情深已故 2021-02-04 21:30

I am curious what others think about this problem...

I have been going back and forth in the past few days about using QuerySet.update() versus ModelI

相关标签:
2条回答
  • 2021-02-04 21:43

    The problem you described about Django Admin is essentially about updating a model instance using an outdated copy. It is easy to fix by adding a version number to each model instance and increment the number on each update. Then in the save method of the model, just make sure what you are saving is not behind what is already in the database.

    I want to make sure when there are parallel writes to the same object, each write updates a different fields, they don't overwrite each other's values.

    Depending on the application, this may or may not be a sensible thing. Saving a whole model even if only a single field is updated can often avoid breaking integrity of data. Thinking about the following example about travel itinerary of three-leg flight. Assume there is an instance of three fields representing three legs and three fields are SF->LA, LA->DC, DC->NY. Now if one update is to update the first two legs to SF->SD, SD->DC, and another update is to update the last two legs to LA->SJ, SJ->NY, and if you allow both to happen with update instead of saving the full model instance, you would come out with a broken itinerary of SF->SD, LA->SJ, SJ->NY.

    0 讨论(0)
  • 2021-02-04 21:59

    The main reason for using QuerySet.update() is that you can update more than one object with just one database query, while every call to an object's save method will hit the database!

    Another point worth mentioning is, that django's pre_save & post_save signals are only sent when you call an object's save-method, but not upon QuerySet.update().

    Coming to the conflict issues you describe, I think it would also be irritating if you hit 'save' and then you have to discover that afterwards some values are the same as when you changed them, but some that you left unchanged have changed?!? Of course it's up to you to modify the admin's save_model or the object's save method to the bahaviour you suggest.

    0 讨论(0)
提交回复
热议问题