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

后端 未结 3 1970
故里飘歌
故里飘歌 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:20

    You could use Q objects to constuct a query like this:

    from django.db.models import Q
    
    ob_list = data.objects.filter(reduce(lambda x, y: x | y, [Q(name__contains=word) for word in list]))
    

    Edit:

    reduce(lambda x, y: x | y, [Q(name__contains=word) for word in list]))
    

    is a fancy way to write

    Q(name__contains=list[0]) | Q(name__contains=list[1]) | ... | Q(name__contains=list[-1])
    

    You could also use an explicit for loop to construct the Q object.

提交回复
热议问题