Vla*_* T. 4 django django-queryset
我想根据这个和这个'blog/'文档从多个对象的字段中删除子字符串:slug
>>> 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
Run Code Online (Sandbox Code Playgroud)
我尝试添加str()到最后一个字符串,它通过了,没有错误:
>>> Blog.objects.update(slug=p.sub('', str(F('slug'))))
Run Code Online (Sandbox Code Playgroud)
但它插入(DEFAULT: )到slug所有对象的字段中。
有什么建议么?
要在 Django 中使用查询集的正则表达式一次更新多个对象,您可以使用Func 表达式来访问数据库中的正则表达式函数:
django.db.models import F, Func, Value
pattern = Value(r'blog(/?)') # the regex
replacement = Value(r'new-blog-slug\1') # 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(),
)
)
Run Code Online (Sandbox Code Playgroud)
检查您的数据库供应商文档以获取详细信息和特定功能支持。
r''在pattern和中使用原始字符串replacement以避免转义反斜杠。
replacement使用1 到 9\n时引用匹配的子字符串。n
您可以使用表达式从每个实例的字段中F提供pattern,replacement和:flags
pattern = F('pattern_field')
replacement = F('replacement_field')
flags = F('flags_field')
Run Code Online (Sandbox Code Playgroud)
您还可以使用Func表达式来进行注释。
目前有一个开放的拉取请求,要求在 Django 中添加正则表达式数据库功能。合并后,您可能会在下面使用RegexpReplace、RegexpStrIndex和RegexpSubstr函数表达式,django.db.models.functions以使您的代码更加简洁,并在数据库供应商之间拥有统一的单一 API。
| 归档时间: |
|
| 查看次数: |
3034 次 |
| 最近记录: |