Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLALchemy dynamic filter_by

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;
like image 370
user851094 Avatar asked Apr 27 '15 01:04

user851094


2 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)
like image 139
Wolph Avatar answered Nov 03 '22 00:11

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)
like image 36
Jie Wu Avatar answered Nov 02 '22 23:11

Jie Wu