使用字符串替换的Django批量更新replace方法的使用

时间:2022-01-12 10:33:57 类型:python
字号:    
#方法一:
for entry in ExampleModel.objects.all():
    entry.string_field = entry.string_field.replace('old text', 'new text', 1)
    entry.save()

#方法二:
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',
    )
)

#方法三:

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'))
)

#方法四:
#Django直接调用原生方法


<