Django:使用regex更新多个对象 [英] Django: Update multiple objects with regex
本文介绍了Django:使用regex更新多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据this和this文档从多个对象的slug
字段中删除'blog/'
子字符串:
>>> import re
>>> from django.db.models import F
>>> p = re.compile('blog/')
>>> Blog.objects.update(slug=p.sub('', F('slug')))
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: expected string or buffer
我尝试将str()
添加到最后一个字符串,但它通过时没有错误:
>>> Blog.objects.update(slug=p.sub('', str(F('slug'))))
但它将(DEFAULT: )
插入到所有对象的slug
字段中。
有什么建议吗?
推荐答案
要使用查询集上的正则表达式同时更新django中的多个对象,您可以使用Func expression访问数据库中的regex函数:
django.db.models import F, Func, Value
pattern = Value(r'blog(/?)') # the regex
replacement = Value(r'new-blog-slug1') # replacement string
flags = Value('g') # regex flags
Blog.objects.update(
slug=Func(
models.F('slug'),
pattern, replacement, flags,
function='REGEXP_REPLACE',
output_field=models.TextField(),
)
)
有关详细信息和特定功能支持,请查看数据库供应商文档。
在pattern
和replacement
中使用原始字符串r''
以避免必须转义反斜杠。
使用
和n
从1到9引用replacement
中的匹配子字符串。
您可以使用F
表达式提供每个实例的pattern
、replacement
和flags
FROM字段:
pattern = F('pattern_field')
replacement = F('replacement_field')
flags = F('flags_field')
您还可以使用Func
表达式进行批注。
django.db.models.functions
下拥有RegexpReplace
、RegexpStrIndex
和RegexpSubstr
函数表达式,以使您的代码更加简洁,并且拥有跨DB供应商统一的单一API。
这篇关于Django:使用regex更新多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文