问题
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