In Django, I can have queries that look like this:
from django.db.models import Value
from django.db.models.functions import Replace
MyModel.objects.update(description=Replace("description", Value("old_1"), Value("new_1")))
MyModel.objects.update(description=Replace("description", Value("old_2"), Value("new_2")))
The first .update will go through the database, look for the "old_1" substring in the description field, and replace it with the "new_1" substring. The second .update call will do the same thing for the old_2 substring, replacing it with the new_2 substring.
Can this be done in a single query?
>Solution :
You can perform the Replace [Django-doc] twice:
from django.db.models import Value
from django.db.models.functions import Replace
MyModel.objects.update(
description=Replace(
Replace('description', Value('old1'), Value('new1')),
Value('old2'),
Value('new2'),
)
)
We can make a utility function to build such expression:
from functools import reduce
from django.db.models.functions import Replace
def MultiReplace(expr0, *kvs):
return reduce(lambda e, kv: Replace(e, *kv), kvs, expr0)
Then we can nest these with:
MyModel.objects.update(
description=MultiReplace(
'description',
(Value('old1'), Value('new1')),
(Value('old2'), Value('new2')),
)
)