2016-11-18 57 views
0

this question的例子,我有一個小flask認爲,基於查詢字符串參數過濾數據:蟒蛇:燒瓶SQLAlchemy的結合filter_by和_in

@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 

這偉大工程時,有各自的只有1個occurence鍵入request.args。我如何擴展這個來處理每個關鍵字的多個值? e.g /regs?foo=1&foo=2

是否有同時適用filter_byin_()

感謝

+0

你不能在順序方式中使用'filter_by()'和'in()'嗎? – RichArt

+0

@RichArt使用v而不是v [0]引發sqlalchemy.exc.InterfaceError – jprockbelly

+0

Python字典不支持重複鍵。可能是NPE幫助你的答案:http://stackoverflow.com/questions/10664856/make-dictionary-with-duplicate-keys-in-python – RichArt

回答

0

最好的解決方案,我能想出是在每個參數和連鎖迭代過濾器一起的方式。

不完美,但它的作品。

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