2

为了生成一些查询,我使用以下代码:

query_words = ['word1', 'word2', 'word3', ...]
query_array = [Q(text__icontains=w) for w in query_words]
try:
  query = query_array.pop()
  for q in query_array:
    query |= q #or query &= q
  result = SomeModel.objects.filter(query)
except:
  result = SomeModel.objects.none()

我确信有一种方法可以写得更紧凑。如何?我试过使用reduce函数:

...
query = reduce(lambda res, q: res |= q, query_array, query_array.pop())
...

但是我遇到了语法错误。怎么了?

4

1 回答 1

4

你可以试试,

from operator import or_
query_words = ['word1', 'word2', 'word3', ...]
query_array = [Q(text__icontains=w) for w in query_words]
reduce(or_, query_array)
于 2013-08-19T09:35:39.683 回答