开发者

Django query with contains and keywords

开发者 https://www.devze.com 2023-02-02 02:48 出处:网络
I have some keywords in one string splitted with \" \". I have also table with column name. How can I get all records which will have in na开发者_StackOverflow社区me part of one keyword?

I have some keywords in one string splitted with " ". I have also table with column name. How can I get all records which will have in na开发者_StackOverflow社区me part of one keyword?

Example:

keywords = 'test split el'

And if I have in records 'test2' 'element' and 'show' the query should return 'test2' and 'element'.


Table.objects.filter(name__in=keyword.split(' '))

OK, that was wrong. I don't know, if this can be accomplished in a one liner or single sql query. The more obvious way is like this, but I don't know, if this is optimal:

result = []
for keyword in keywords.split(' '):
    result += list(Table.objects.filter(name__icontains=keyword))

Ok, this can be done in a single query, but I am not exactly sure how. You can try this:

   final_pred = Q()
   for pred in [Q(name__icontains=keyword) for keyword in keywords.split(' ')]:
     final_pred = final_pred | pred;
   Table.objects.filter(final_pre)
0

精彩评论

暂无评论...
验证码 换一张
取 消