Jason Jason - 3 months ago 19
reST (reStructuredText) Question

Chaining queries in MongoEngine

I'm implementing a REST API for a standard CRUD app. In one example, to get a list of users, clients can call:

GET api.site.com/users
(and optionally)
?name=x
phone=x
email=x


Passing the above optional parameters filters the users I search for.

I'm trying to implement this logic in Python. I'm thinking of chaining sub-queries, like so:

Given:

users = User.objects()


Then:

if 'name' in request.args:
users = users.objects(name = request.args['name'])


And:

# List of users is smaller after filtering by name
if 'phone' in request.args:
users = users.objects(phone = request.args['phone'])


And:

# List of users is smaller after filtering by phone
if 'email' in request.args:
users = users.objects(email = request.args['email'])


But the method isn't available, and I can't find out how to do this by checking the MongoEngine API reference or User Guide or tutorial.

What can I do to chain sub-queries in MongoEngine?

Answer

Since, mongoengine supports keyword arguments to the objects call, you can create a dictionary, with the keys as field_names, and values as field_values. And then use this dictionary while querying. For example:

query = {}

if 'name' in request.args:
    query['name'] = request.args['name']

if 'phone' in request.args:
    query['phone'] = request.args['phone']

if 'email' in request.args:
    query['email'] = request.args['email']

user = User.objects(**query)

The above is just a sample, you might want to add security measures, and maybe have a default query, depending on your app.