I am trying to update and modify a string field Django\'s ORM. The equivalent SQL to do this is:
UPDATE example_table SET string_field = REPLACE(string_fiel
You could make your own F
-like object to represent the string replacing in SQL. Here is a proof of concept:
from django.db.models.expressions import ExpressionNode
class StringReplaceF(ExpressionNode):
def __init__(self, field, replace_from, replace_to):
self.field = field
self.replace_from = replace_from
self.replace_to = replace_to
super(StringReplaceF, self).__init__()
def evaluate(self, evaluator, qn, connection):
return (
"REPLACE({}, %s, %s)".format(self.field),
(self.replace_from, self.replace_to)
)
>>> f = StringReplaceF('string_field', 'old text', 'new text')
>>> ExampleModel.objects.update(string_field=f)
You'd need to do a bit more work with the class if you need it to behave nicely with other F
objects, but then again, the existing F
objects don't seem to work with strings anyway.