Django ORM - .update(…) with an extra(…) and F(…)

守給你的承諾、 提交于 2019-12-11 02:13:08

问题


I want to do one sql query to update a lot of models in a Django site. I want to change one char column/field to be based on the id and some text, in MySQL (which this site is), I'd do that with "UPDATE table SET blah = 'prefix'||id||'suffix'".

My first attempt of doing this in Django was:

Model.objects.update(blah='prefix'+F('id')+'suffix')

But that tries to give MySQL a +, not a || operator.

My next attempt was to use the .extra(…) like so:

Model.objects.extra(select={'newvalue':'"prefix"||id||"suffix"'}).update(blah=F('new_value'))

But the F(…) is unable to see the new field from the select.

Is there anyway to do this without breaking down to raw SQL?


回答1:


Nope. Django's ORM is multi db compilant. It is not shipped with custom db features such as this one.




回答2:


If I understood your question right, this might help:

blah = '%s %s %s' %(prefix, id, suffix)

Model.object.update(blah=blah)


来源:https://stackoverflow.com/questions/13581346/django-orm-update-with-an-extra-and-f

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