简体   繁体   English

python:flask-sqlalchemy结合filter_by和_in

[英]python: flask-sqlalchemy combine filter_by and _in

Following the example in this question I have a little flask view that filters data based on querystring arguments: 此问题的示例之后,我有一个小flask视图,该视图根据querystring参数过滤数据:

@app.route('/regs')
def regs_data():

    #check what data is available
    #REGS is a sqlalchemy model
    cols = REGS.__table__.columns.keys()

    kwargs = {}
    for k, v in request.args.lists():
        if k not in cols:
            abort(400, "helpful err msg")

        #takes only first occurrence
        kwargs[k]=v[0]

    my_query = REGS.query.filter_by(**kwargs).all()

    #....modify the query data for return

    return the_data_as_json

This works great for when there is only 1 occurence of each key in request.args . request.args中每个键只有1次出现时,这非常request.args How can I extend this to cope with multiple values for each keyword? 如何扩展此范围以应对每个关键字的多个值? eg /regs?foo=1&foo=2 例如/regs?foo=1&foo=2

Is there a way to apply both filter_by and in_() 有没有办法同时应用filter_byin_()

Thanks 谢谢

The best solution I could come up with is to iterate over each of the arguments and chain the filters together. 我能想到的最好的解决方案是遍历每个参数并将过滤器链接在一起。

Not quite as neat but it works. 不太整洁,但可以。

def regs_data():

    #get allowed data names
    cols = REGS.__table__.columns.keys()

    #make base query object
    my_query = REGS.query

    for k, v in request.args.lists():
        if k not in cols:
            abort(400, "helpful err msg")

        #chain together filters for each arg 
        my_query  = my_query.filter(getattr(REGS, k).in_(tuple(v)))

     #fire the query
     data = my_query.all()


    #....modify the query data for return

    return the_data_as_json

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

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