mysql 替换的 Django 查询集

Django Queryset for mysql replace

django 中是否有任何 queryset 等价于以下查询。

UPDATE table
SET field = REPLACE(field, 'string', 'anothervalue')
WHERE field LIKE '%string%';

在 Django 文档中查看 contains and icontains

lst = Model.objects.filter(field__icontains="string")
for i in lst: i.field = 'anothervalue'; i.save()

我找到了解决方案。我们需要使用 Replace 数据库函数。如下所示。

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

Model.objects.update(field=Replace(
    'field', Value('string'), Value('anothervalue')
))

了解更多信息official docs.