Skip to content Skip to sidebar Skip to footer

In Django, How To Find A Term That Is Part Of A String Instead Of Containing That String?

For example, there are three rows under two fields in my table like this id name ------- 1 brown cat 2 black dog 3 person And here comes a string, or a sentence: A brown cat ju

Solution 1:

Following query will do:

>>> sentence = 'A brown cat jumps over a person'>>> MyModel.objects.extra(where={"%s like CONCAT('%%', `name` ,'%%')"}, 
...                       params=[sentence]).values()
[{'id': 1L, 'name': u'brown cat'}, {'id': 3L, 'name': u'person'}]

Solution 2:

You can do this:

importoperator
from django.db.models import Q

sentence = 'A brown cat jumps over a person'
queryset = MyModel.objects.filter(reduce(operator.or_, (Q(myfield__icontains=word) for word in sentence.split())))

Solution 3:

I don't think this is possible with the Django ORM, but it's definitely doable with raw SQL. Here's a working query:

SELECT id
FROMtableWHERE'A brown cat jumps over a person'LIKE'%'|| name ||'%'

The trick is to use the column as the search phrase. This should be reasonably database independent. You could use a QuerySet's extra method to limit the use of raw SQL to a minimum.

Post a Comment for "In Django, How To Find A Term That Is Part Of A String Instead Of Containing That String?"