python - 使用 Q 自动生成 django 查询

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

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

最佳答案

你可以尝试

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

关于python - 使用 Q 自动生成 django 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18310599/

相关文章:

python - Python 如何使用 Gunicorn 和 Kubernetes 进行扩展?

Hadoop:Reducer 将 Mapper 输出写入输出文件

django - AWS 上的多容器 Docker

java - Hadoop错误失败AI.java.lang.NumberFormatException:空字符串几乎完成后

javascript - 使用 Array.reduce 的奇怪结果

Python weave 来加速我们的代码

python - 在 sqlalchemy 中按 row_number 过滤

python - 如何在 Seaborn FacetGrid 中制作正方形热图

python - 是否可以将参数传递给 Django 模板中的模型类方法?

python - Django 自连接与外键(ORM)