szaman
szaman

Reputation: 6756

Django query with contains and keywords

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 name 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'.

Upvotes: 3

Views: 1953

Answers (1)

gruszczy
gruszczy

Reputation: 42188

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)

Upvotes: 7

Related Questions