SQLAlchemy - “Dynamic Filter”

后端 未结 3 1747
被撕碎了的回忆
被撕碎了的回忆 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 17:53

    I assume you are using the ORM.

    in that case, the filter function returns a query object. You can conditionaly build the query by doing something like

    query = Session.query(schema.Object).filter_by(attribute=value)
    if condition:
        query = query.filter_by(condition_attr=condition_val)
    if another_condition:
        query = query.filter_by(another=another_val)
    
    #then finally execute it
    
    results = query.all()
    
    0 讨论(0)
  • 2020-12-06 17:54

    The function filter(*criterion) means you can use tuple as it's argument, @Wolph has detail here: SQLALchemy dynamic filter_by for detail

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题