SQLAlchemy - “Dynamic Filter”

后端 未结 3 1760
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 17:22

I have just started using SQLAlchemy. I decided to use it because I was using a lot of string expression in the middle of my sqlite queries.

So, that is my problem.

3条回答
  •  忘掉有多难
    2020-12-06 18:01

    if we speak of SQLAlchemy core, there is another way:

    from sqlalchemy import and_
    
    
    filters = [table.c.col1 == filter1, table.c.col2 > filter2]
    query = table.select().where(and_(*filters))
    

    If you're trying to filter based on incoming form criteria:

    form = request.form.to_dict()
    filters = []
    for col in form:
        sqlalchemybinaryexpression = (getattr(MODEL, col) == form[col])
        filters.append(sqlalchemybinaryexpression)
    query = table.select().where(and_(*filters))
    

    Where MODEL is your SQLAlchemy Model

提交回复
热议问题