Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用Q自动生成django查询_Python_Django_Reduce_Django Q - Fatal编程技术网

Python 使用Q自动生成django查询

Python 使用Q自动生成django查询,python,django,reduce,django-q,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_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())
...
但是我有一个语法错误。 怎么了?

你可以试试

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

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

其中or来自于like方法。你能提供一些参考资料吗?or从何而来。你能给我一些推荐信吗。