pythonmongoengine

building a dynamic query for mongoengine


I am trying to interface with mongoengine and extract out posts based on different inputs. At first I was simply running a for loop with a modulatory query and running said query every time. However following reading, I feel a more efficient way would be to perform the query using the | operand and running the query once. I can do this simply if the query is static but as the number of items to be filtered could vary, I am trying to setup a more dynamic approach

current code setup

console_list = []
for console in console_list:
    query = Q(**{f'{console}__company': company_name})
    console_list .extend(console_document.objects(query))

I attempted the following with great success

query = Q(**{f'Dreamcast__company': company_name}) | Q(**{f'Playstation__company': company_name})
console_list .extend(console_document.objects(query))

but when it comes to building this I receive an error

query = Q(**{f'{console}__company': company_name})
for idx, console in enumerate(console_list):
    if idx==0:
        continue
    query += Q(**{f'{console}__company': company_name})

the error states

TypeError: unsupported operand type(s) for +=: 'QCombination' and 'Q'

which tells me that string comprehension with join will also not work. So how to dynamically generate these Qcombinations?


Solution

  • I figured it out.

    The most efficient way to perform this concatenation is to use the functools reduce function and map. Doing so with the operand of interest will generate the QCombination query.

    functools.reduce(Q.__or__, map(lambda console: Q(**{f'{console}__company': company_name}), console_list))