django filter icontains match whole words only

半腔热情 提交于 2019-12-18 16:45:24

问题


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.

my query looks like this

MyModel.objects.filter(title__icontains=search_word)

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.


回答1:


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.

In python (sqlite) the regexp would be :

\b(word)\b

In Mysql you have :

mysql> SELECT 'a word a' REGEXP '[[:<:]]word[[:>:]]';   -> 1
mysql> SELECT 'a xword a' REGEXP '[[:<:]]word[[:>:]]';  -> 0



回答2:


In case you have angularjs and REST service implemented with tastypie or DRF, you can filter by whole words as $http.get(uri, {'params': {'display_name__iregex': '[[:<:]]word[[:>:]]'})

of course, display_name should be enabled to filtering in Tastypie resource's Meta class as filtering = {'display_name': ALL,}




回答3:


It sounds like you want a Case-insensitive exact match.

MyModel.objects.filter(title__iexact=search_word)

http://docs.djangoproject.com/en/dev/ref/models/querysets/#lookup-iexact



来源:https://stackoverflow.com/questions/2958214/django-filter-icontains-match-whole-words-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!