Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can Django's Replace be used to replace multiple substrings at once?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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')),
    )
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading