Tortoise-ORM使用filter查询时忽略值为None的参数
作者:互联网
首先看一个官网的filter示例
Users.filter(id=user_id, name=user_name).all()
在如下实际应用中,我们需要忽略参数值为None的情况,不传参表示查询全部数据
@app.get('/users', response_model=User_Pydantic)
async def get_users(user_name: str|None=None, email: str|None=None):
db_user = await Users.filter(
user_name__contains = user_name,# __contains表示模糊查询
email__contains = email
).all()
return db_user
此时请求中不传参,user_name=None
,email=None
,那么tortoise-orm查询满足user_name为null且email为null的数据,虽然tortoise-orm这样设计更直观,但这样这显然达不到我们想要的效果,那应该怎么做呢,其实很简单,我们可以将值为None的参数过滤掉
@app.get('/users', response_model=User_Pydantic)
async def get_users(user_name: str|None=None, email: str|None=None):
args = {'user_name__contains': user_name, 'email__contains': email}
args_ignore_none = {key: value for key, value in args.items() if value is not None}
db_user = await Users.filter(**args_ignore_none).all()
return db_user
这样就可以啦,貌似看起来不美观,我们可以将过滤参数封装起来,提高代码复用性
# ./users.py
from .common import ignore_none
@app.get('/users', response_model=User_Pydantic)
async def get_users(user_name: str|None=None, email: str|None=None):
db_user = await Users.filter(**ignore_none(
user_name__contains = user_name,
email__contains = email
)).all()
return db_user
# ./common.py
def ignore_none(**args):
return {key: value for key, value in args.items() if value is not None}
参考链接
https://github.com/chdxia/lrtest-api
标签:__,None,Tortoise,contains,值为,user,email,name 来源: https://www.cnblogs.com/chdxia/p/16527150.html