使用字符串替换的Django批量更新 [英] Django bulk update with string replace
问题描述
我正在尝试更新和修改Django ORM的字符串字段。与此等效的SQL是:
UPDATE example_table SET string_field = REPLACE(string_field,'old text','new text' );
通过该查询,我希望旧文本
和旧文本更多文本
替换为新文本
和新文本更多文本
,分别用于 string_field
列中的所有条目。
批量更新()似乎很有希望,但不允许我仅修改其中的一部分字段,并且 F()表达式仅实现数字更改,而不是字符串替换。我还查看了使用原始查询运行上述SQL,但这似乎是一个横冲直撞的行为(特别是因为F()存在对数字执行相同的功能),而我无法让它们实际执行。
我结束了这个,但是当我知道有一行SQL语句可以执行所有额外的查询时,这似乎很可耻。
用于ExampleModel.objects.all()中的条目:
entry.string_field = entry.string_field.replace('old text','new text',1)
entry.save()
此功能在Django的ORM中是否不存在用于字符串的功能?
相关SO问题:
使用django 1.9进行测试
<$ p $来自django.db.models的p>
导入F,函数,值
ExampleModel.objects.filter(< condition>)。update(
string_field = Func(
F('string_field'),
Value('old text'),Value('new text'),
function ='replace',
)
)
更新Django 2.1
https://docs.djangoproject.com/zh-CN/2.2/ ref / models / database-functions /#replace
from django.db.models import Value
从django.db.models.functions import替换
ExampleModel.objects.filter(< condition>)。update(
string_field = Replace('name',Value('old text' ),Value('new text'))
)
I am trying to update and modify a string field Django's ORM. The equivalent SQL to do this is:
UPDATE example_table SET string_field = REPLACE(string_field, 'old text', 'new text');
With that query, I expect old text
and old text more text
to be replaced with new text
and new text more text
respectively, for all the entries in the string_field
column.
Bulk update() seems promising, but doesn't allow me to modify only part of the field, and F() expressions only implement numeric changes, not string replace. I also looked at using raw queries to run the above SQL, but that seems like a sideways hack (especially since F() exists to do the same functionality on numbers), and I couldn't get them to actually execute.
I ended up with this, but it seems a shame to execute all the extra queries when I know there's a one line SQL statement to do it.
for entry in ExampleModel.objects.all():
entry.string_field = entry.string_field.replace('old text', 'new text', 1)
entry.save()
Does this feature not exist in Django's ORM for strings yet? Is there something I overlooked in the docs?
Related SO questions:
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'))
)
这篇关于使用字符串替换的Django批量更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!