django过滤器图标只匹配整个字 [英] django filter icontains match whole words only
问题描述
我正在使用过滤器icontain来搜索单词,但我只希望它匹配整个单词。例如如果我搜索肝脏,我不希望它返回送货。
I am using the filter icontains to search for words but I only want it to match whole words. e.g. if I searched for liver I wouldn't want it returning delivery.
我的查询看起来像这样
MyModel.objects.filter(title__icontains=search_word)
过滤器 __搜索
但是这不会带来3个字符或更少的结果,我正在构建的网站包含很多可以搜索的网站,例如'bbc'
I have seen the filter __search
but this does not bring back results with 3 characters or less and the site I am building contains a lot of these which could be searched for, e.g. 'bbc'
我无法访问数据库,但是如果有人知道如何在代码中禁用此代码,那么我很乐意将其用作
I do not have access to the db but if anyone knows how I can disable this in the code then I would be happy to switch to using this as an alternative.
推荐答案
正则表达式通常是足够的:
http://docs.djangoproject.com/en/dev/ref/models/querysets/#regex
Regexp are usually enough : http://docs.djangoproject.com/en/dev/ref/models/querysets/#regex
请注意,正则表达式语法是使用数据库后端的语法。
Please note that the regular expression syntax is that of the database backend in use.
python(sqlite)正则表达式将是:
In python (sqlite) the regexp would be :
\b(word)\b
在Mysql中有:
mysql> SELECT 'a word a' REGEXP '[[:<:]]word[[:>:]]'; -> 1
mysql> SELECT 'a xword a' REGEXP '[[:<:]]word[[:>:]]'; -> 0
这篇关于django过滤器图标只匹配整个字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!