SQLALchemy dynamic filter_by

Question:

I know you can build dynamic filters for queries for SQLAlchemy by supplying **kwargs to filter_by.

For example

    filters = {'id': '123456', 'amount': '232'}
    db.session.query(Transaction).filter_by(**filters)

Below is my question:

What if I need to query by “greater than” or “less than” clauses?
For example (raw SQL):

 select * from transaction t 
 where t.amount > 10 and t.amount < 100;
Asked By: user851094

||

Answers:

Instead of using filter_by I would recommend using filter, it gives you a lot more options.

For example (from the manual):

db.session.query(MyClass).filter(
    MyClass.name == 'some name',
    MyClass.id > 5,
)

In relation to your case:

filters = (
    Transaction.amount > 10,
    Transaction.amount < 100,
)
db.session.query(Transaction).filter(*filters)
Answered By: Wolph
def get_filter_by_args(dic_args: dict):
    filters = []
    for key, value in dic_args.items():  # type: str, any
        if key.endswith('___min'):
            key = key[:-6]
            filters.append(getattr(model_class, key) > value)
        elif key.endswith('___max'):
            key = key[:-6]
            filters.append(getattr(model_class, key) < value)
        elif key.endswith('__min'):
            key = key[:-5]
            filters.append(getattr(model_class, key) >= value)
        elif key.endswith('__max'):
            key = key[:-5]
            filters.append(getattr(model_class, key) <= value)
        else:
            filters.append(getattr(model_class, key) == value)
    return filters

dic_args = {
    'is_created': 1,
    'create_time__min': 1588125484029,
}
filters = get_filter_by_args(dic_args)
lst = session.query(model_class).filter(*filters)
Answered By: Jie Wu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.