SQLALchemy动态filter_by

时间:2015-04-27 01:45:42

标签: python orm sqlalchemy

我知道您可以通过向**kwargs提供filter_by来为SQLAlchemy的查询构建动态过滤器。

例如

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

以下是我的问题:

如果我需要查询“大于”或“小于”条款,该怎么办? 例如(原始SQL):

 select * from transaction t 
 where t.amount > 10 and t.amount < 100;

2 个答案:

答案 0 :(得分:16)

我建议您使用filter_by而不是filter,而是为您提供更多选择。

例如(来自手册):

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

就你的情况而言:

filters = (
    Transaction.amount > 10,
    Transaction.amount < 100,
)
db.session.query(Transaction).filter(*filters)

答案 1 :(得分:2)

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)