[Django]-Django query with contains and keywords

7👍

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)

Leave a comment