Django partial update

ぐ巨炮叔叔 提交于 2021-01-03 08:36:27

问题


I have two threads, one which runs something like update t set ColA=foo and the other runs update t set ColB=foo. If they were doing raw SQL statements there would be no contention, but since Django gets and saves the entire row, a race condition can occur.

Is there any way to tell Django that I just want to save a certain column?


回答1:


You are correct that save will update the entire row but Django has an update which does exactly what you describe.

https://docs.djangoproject.com/en/stable/ref/models/querysets/#update




回答2:


Update old topic.

Now, we have update_fields argument with save:

If save() is passed a list of field names in keyword argument update_fields, only the fields named in that list will be updated.

https://docs.djangoproject.com/en/stable/ref/models/instances/#specifying-which-fields-to-save

product.name = 'Name changed again'
product.save(update_fields=['name'])



回答3:


I think your only option to guarantee this is to write the raw SQL by hand by using Manager.raw() or a cursor depending on which one is more appropriate.



来源:https://stackoverflow.com/questions/7528683/django-partial-update

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