Dynamic field and operator in MongoEngine query

1.9k Views Asked by At

I have a application where users should be able to build complex search queries.The problem is that when I'm building a query with the Q object I can't find a way to make the parameters dynamic.

Users.objects.filter(age__gte=18)

Given the query above, I would want to make age and gte dynamic. I get them in str format from a HTML form, but how can I translate them into a real parameter? I want something along the lines of this:

Users.objects.filter('{}__{}=18'.format(field, operator))
1

There are 1 best solutions below

0
On

You forgot that python can take as parameters list *args and dict **kwargs of parameters. So for your case:

Users.objects.filter(**{'{}__{}'.format(field, operator): 18})