SQLALchemy 动态 filter_by

SQLALchemy dynamic filter_by

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

例如

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

下面是我的问题:

如果我需要通过"greater than"或"less than"子句查询怎么办? 例如(原始SQL):

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

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

例如(来自手册):

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)
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)