Django ORM - 喜欢的百分号 [英] Django ORM - percent sign for like
问题描述
在我的网站用户应该有能力过滤数字,如 * 123 * 321 *
,匹配666 123 555 321 111或 LIKE'%123%321%'
。
On my site user should have an ability to filter numbers, like *123*321*
, that will match "666 123 555 321 111" or LIKE '%123%321%'
.
默认情况下django's orm转义 %-sign 。我可以使用正则表达式或原始查询,但是是否有一些解决方法?
By default django's orm escapes %-sign. I can use regex, or raw query, but is there some workaround?
UPD:我将其放在这里显示另一种方式。
UPD: i'll place it here for displaying another way.
integer_search = [] # for colorizing found substrings
if actual['integer']:
integer_match = filter(None, actual['international'].split('*'))
integer_search = integer_match
integer_match = ''.join('%s[[:digit:]]*' % i for i in integer_match)
integers = integers.filter(international__regex=integer_match)
推荐答案
p>是的,Django替换所有的%
和 _
。从文档:
Yes, Django replaces all the %
and _
. From docs:
这意味着事情应该直观地工作,所以抽象不会
泄漏。例如,要检索包含百分比
符号的所有条目,只需使用百分号作为任何其他字符
This means things should work intuitively, so the abstraction doesn't leak. For example, to retrieve all the entries that contain a percent sign, just use the percent sign as any other character
我建议您使用额外的方法。它不是真正的原始sql,虽然看起来很古怪:
I would recommend you to use extra method. It is not really raw sql, although looks hacky:
YourModel.objects.extra(where=['title LIKE %s'], params=['%123%321%'])
这篇关于Django ORM - 喜欢的百分号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!