Django: save() vs update() to update the database?

前端 未结 6 1916
醉酒成梦
醉酒成梦 2020-12-12 18:55

I\'m writing a Django app, and I need a function to update a field in the database. Is there any reason to do one of these methods rather than the other?

de         


        
6条回答
  •  感动是毒
    2020-12-12 19:38

    Both looks similar, but there are some key points:

    1. save() will trigger any overridden Model.save() method, but update() will not trigger this and make a direct update on the database level. So if you have some models with overridden save methods, you must either avoid using update or find another way to do whatever you are doing on that overridden save() methods.

    2. obj.save() may have some side effects if you are not careful. You retrieve the object with get(...) and all model field values are passed to your obj. When you call obj.save(), django will save the current object state to record. So if some changes happens between get() and save() by some other process, then those changes will be lost. use save(update_fields=[.....]) for avoiding such problems.

    3. Before Django version 1.5, Django was executing a SELECT before INSERT/UPDATE, so it costs 2 query execution. With version 1.5, that method is deprecated.

    In here, there is a good guide or save() and update() methods and how they are executed.

提交回复
热议问题