user1689543
user1689543

Reputation: 11

mongoengine - dynamically generating Q()

Is there a way to dynamically generate a Q() other than using eval().

Current method with eval():

q = eval("Q(" + q_arg + mode + "=args[arg])")

Where mode is "_in" or "_nin".

This works, just trying to do it without eval()

Upvotes: 1

Views: 576

Answers (1)

Ross
Ross

Reputation: 18111

Q objects, like any python class can just take kwargs - which can be a dictionary, so you can just build the dictionary and pass it in eg:

kwargs = {}

# Build the key and add it to the kwargs dict
key = "%s%s" % (q_arg, mode)
kwargs[key] = args[arg]

# Pass kwargs to Q
q = Q(**kwargs)

Upvotes: 3

Related Questions