Django bulk update with string replace

旧时模样 提交于 2019-11-30 04:52:56

Tested with django 1.9

from django.db.models import F, Func, Value

ExampleModel.objects.filter(<condition>).update(
    string_field=Func(
        F('string_field'),
        Value('old text'), Value('new text'),
        function='replace',
    )
)

UPDATE Django 2.1 https://docs.djangoproject.com/en/2.2/ref/models/database-functions/#replace

from django.db.models import Value
from django.db.models.functions import Replace

ExampleModel.objects.filter(<condition>).update(
    string_field=Replace('name', Value('old text'), Value('new text'))
)

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.

New in Django 2.1 - Replace database function

Your example can now be expressed most easily via:

ExampleModel.objects.update(string_field=Replace('string_field', Value('old_text'), Value('new_text')))

Django 2.2 support bulk update, can you using function that one.

Check this one : https://docs.djangoproject.com/en/2.2/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create

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