10

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.

Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
John
  • 21,047
  • 43
  • 114
  • 155
  • 1
    Perhaps you could use [regex](http://docs.djangoproject.com/en/dev/ref/models/querysets/#iregex) instead, or add spaces at start and end of your `search_word` string? – Davor Lucic Jun 02 '10 at 13:59
  • I was thinking about adding spaces but if the title was only 1 word or the word appeared at the beginning or end of the title then this would not work. How would I do it via regex? – John Jun 03 '10 at 08:34

3 Answers3

6

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
leplatrem
  • 1,005
  • 13
  • 25
  • 1
    this along with http://docs.djangoproject.com/en/dev/ref/models/querysets/#iregex solved my problem – John Nov 30 '10 at 14:55
0

In case you have and REST service implemented with 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,}

Aleksey
  • 109
  • 1
  • 5
-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

Jason Leveille
  • 1,190
  • 5
  • 10
  • this would not work as I still want to search for part of a string but iexact requires the whole string to match. for example if my title was 'this is a test title' I would want to find this if I searched for 'test title' – John Jun 03 '10 at 08:33
  • I see. You want it to find 'test title' but not 'est title'. Got it. – Jason Leveille Jun 03 '10 at 11:37