flask 多条件查询

筛选的时候会遇到多个筛选条件,但都是非必填的
把存在的筛选条件添加到数组中,然后进行解包
最后把解包后的数据添加到筛选条件中

@api.route("/role/list")
def roleList():
    name = request.args.get("name")
    gender = request.args.get("gender")
    attribute = request.args.get("attribute")
    site = request.args.get("site")

    filterList = []

    if name is not None:
        filterList.append(Role.name.like('%'+name+'%'))
    if gender is not None:
        filterList.append(Role.gender == gender)
    if attribute is not None:
        filterList.append(Role.attribute == attribute)
    if site is not None:
        filterList.append(Role.site == site)

    role = Role.query.filter(*filterList).all()

    data = []
    for i in role:
        info = {
            "id":i.id,
            "name":i.name,
            "attribute":i.attribute,
            "head_portrait":i.head_portrait
        }
        data.append(info)

    return jsonify(code="1",msg="成功",data=data)

你可能感兴趣的:(flask 多条件查询)