How to Query model where name contains any word in python list?

后端 未结 3 1967
故里飘歌
故里飘歌 2020-12-23 17:02

Aim to Achieve:

I want all objects where name attribute contains any word from the list.

I have:

list = [\'word1\',\'word2\',\'word3\']
ob_li         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 17:36

    ob_list = data.objects.filter(name__in=my_list)
    

    And BTW, avoid using the variable name "list" (Or any other python standard keyword), lest you get into some weird bugs later.

    Update: (I guess your question was updated too, because when I wrote the answer, I didn't see the part where you wrote you need a contains match and not an exact match)

    You can do that using the regex search too, avoiding many Q expressions (which end up using that many where "and" clauses in the SQL, possibly dampening the performance), as follows:

    data.objects.filter(name__regex=r'(word1|word2|word3)')
    

提交回复
热议问题