Jason
Jason

Reputation: 6926

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?

Upvotes: 4

Views: 1047

Answers (2)

Karloku
Karloku

Reputation: 31

http://docs.mongoengine.org/apireference.html#mongoengine.queryset.QuerySet.__call__ The mongoengine.QuerySet object itself is callable. Chaining queries can be done simply by calling the result queryset.

users = User.objects()

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

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

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

Upvotes: 0

bool.dev
bool.dev

Reputation: 17478

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.

Upvotes: 7

Related Questions