【问题标题】:Autogenerate django query with Q使用 Q 自动生成 django 查询
【发布时间】:2013-08-21 01:27:43
【问题描述】:

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

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

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

【问题讨论】:

    标签: python django reduce django-q


    【解决方案1】:

    你可以试试,

    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_ 来自类似方法。你能提供一些参考吗?
    猜你喜欢
    • 2018-12-19
    • 2015-11-12
    • 2015-02-28
    • 1970-01-01
    • 2021-09-15
    • 2017-03-20
    • 2014-08-12
    • 2012-10-16
    • 2013-02-25
    相关资源
    最近更新 更多