简体   繁体   English

SQLAlchemy - 如何过滤多个动态 OR 值?

[英]SQLAlchemy - How to filter_by multiple dynamic OR values?

I have a pretty reasonable use case: Multiple possible filter_by matches for a single column.我有一个非常合理的用例:单个列的多个可能的 filter_by 匹配项。 Basically, a multiselect JS dropdown on front end posts multiple company industries to the backend.基本上,前端的多选 JS 下拉列表会将多个公司行业发布到后端。 I need to know how to write the SQLAlchemy query and am surprised at how I couldn't find it.我需要知道如何编写 SQLAlchemy 查询,并且对我找不到它感到惊讶。

{ filters: { type: "Industry", minmax: false, value: ["Financial Services", "Biotechnology"] } }
@app.route("/dev/api/saved/symbols", methods=["POST"])
@cross_origin(origin="*")
def get_saved_symbols():
    req = request.get_json()
    # res = None
    # if "minmax" in req["filters"]:
    #     idx = req["filters"].index("minmax")
    #     if req["filters"][idx] == "min":
    #         res = db.session.query.filter(Company[req["filter"]["type"]] >= req["filters"]["value"])
    #     else:
    #         res = db.session.query.filter(Company[req["filter"]["type"]] <= req["filters"]["value"])

    # else:
    res = db.session.query.filter_by(Company[req["filters"]["type"]] == req["filters"]["value"])

    return jsonify(res)

As you can see I am also working on a minmax which is like an above or below filter for other columns like price or market cap.正如你所看到的,我也在研究一个最小值,它类似于价格或市值等其他列的上方或下方过滤器。 However, the multiselect OR dynamic statement is really what I am stuck on...但是,多选 OR 动态语句确实是我所坚持的……

I ended up creating a separate filter function for this that I can than loop over results with.我最终为此创建了一个单独的过滤器函数,然后我可以循环遍历结果。

I will just show the first case for brevity.为简洁起见,我将仅展示第一个案例。 I am sending a list of strings in which I create a list of filters and then use the or_ operator imported from sqlalchemy package.我正在发送一个字符串列表,在其中创建一个过滤器列表,然后使用从 sqlalchemy 包导入的 or_ 运算符。

def company_filter(db, filter_type, filter_value, minmax):
    match filter_type:
        case "industry":
            filter_list = []

            for filter in filter_value:
                filter_list.append(Company.industry == filter)

            return db.query(Company).with_entities(Company.id, Company.symbol, Company.name, Company.monthly_exp).filter(or_(*filter_list))
        ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM