How to match string with database fields in Django?
I have a database with a name
column having data like
'Very big News'
'News'
'something else'
'New Nes'
'Fresh News'
'Something else'
Now given a string of words, how can I find if any of the words in the given string is co开发者_高级运维ntained in the name
field?
For example:
I have a string 'super very news'
. I need to look in my database to see if I have any record such that the name
field contains either 'super'
or 'very'
or 'news'
or 'super very'
or 'very news'
.
Update based on comments. See the query set docs here.
your_search_query = 'super very news'
qset = Q()
for term in your_search_query.split():
qset |= Q(name__contains=term)
matching_results = YourModel.objects.filter(qset)
This creates the equivalent of:
matching_result = YourModel.objects.filter(Q(name__contains='super') |
Q(name__contains='very') |
Q(name__contains='news'))
which produces (roughly) the following SQL in a single query:
select * from your_model where name like '%super%' or name like '%very%' or name like '%news%'
If your word list is small and simple you can write your own lookup table and indexer, otherwise you want a full text database like OpenFTS:
http://openfts.sourceforge.net/
精彩评论