Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django filter icontains match whole words only

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.

like image 206
John Avatar asked Jun 02 '10 13:06

John


People also ask

What is Q filter Django?

Q object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects we can make complex queries with less and simple code. For example, this Q object filters whether the question starts wiht 'what': from django. db.

What is difference between contains and Icontains in Django?

What is difference between contains and Icontains in Django? Definition and Usage The contains lookup is used to get records that contains a specified value. The contains lookup is case sensitive. For a case insensitive search, use the icontains lookup.

What is the purpose of filter () method in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.


1 Answers

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
like image 77
leplatrem Avatar answered Oct 03 '22 03:10

leplatrem