Search code examples
pythondjangoreducedjango-q

Autogenerate django query with Q


for generate some query i use this code:

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

I'm sure there's a way to write this more compact. How? I've tried to use reduce function:

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

But I got a syntax error. What's wrong?


Solution

  • you can try,

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