用Q自动生成django查询

时间:2013-08-19 09:33:19

标签: python django reduce django-q

用于生成一些查询我使用此代码:

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())
...

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

1 个答案:

答案 0 :(得分:3)

你可以尝试,

from operator import or_
query_words = ['word1', 'word2', 'word3', ...]
query_array = [Q(text__icontains=w) for w in query_words]
reduce(or_, query_array)