编程语言
首页 > 编程语言> > python – 在MongoEngine中链接查询

python – 在MongoEngine中链接查询

作者:互联网

我正在为标准CRUD应用程序实现REST API.在一个示例中,要获取用户列表,客户可以调用:

获取api.site.com/users(以及可选)?name = x phone = x email = x

传递上述可选参数可过滤我搜索的用户.

我正在尝试在Python中实现这个逻辑.我正在考虑链接子查询,如下所示:

鉴于:

users = User.objects()

然后:

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

和:

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

和:

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

但是该方法不可用,我无法通过检查MongoEngine API参考或用户指南或教程来了解如何执行此操作.

如何在MongoEngine中链接子查询?

解决方法:

mongoengine supports keyword arguments to the objects call开始,您可以创建一个字典,其键为field_names,值为field_values.然后在查询时使用这个字典.例如:

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)

以上只是一个示例,您可能希望添加安全措施,并且可能有默认查询,具体取决于您的应用程序.

标签:mongoengine,python,mongodb,rest,flask
来源: https://codeday.me/bug/20190825/1720187.html