或多个SQL Alchemy查询过滤器

时间:2015-03-26 22:12:51

标签: python sqlalchemy

所以我正在尝试使用python为sql炼金术调用构建多个过滤器。我

query = MyModel.query

if 'column1' in data:
    try:
        value = int(data['column1'])
    except (TypeError, ValueError):
        pass
    else:
        query = query.filter(MyModel.column1 == value)

if 'column2' in data:
    try:
        value = datetime.utcfromtimestamp(int(data['column2']))
    except (TypeError, ValueError):
        pass
    else:
        query = query.filter(or_(MyModel.column2 >= value))

# etc.

return query

我只是这样做,因为数据对象中的属性会有所不同,我不知道数据对象中的过滤器会得到什么。现在,当我执行查询时...语句 ANDs 两个过滤器,无论我在第二个过滤器查询中放入的还是_ 。为了使查询正常工作,我需要更改什么?

1 个答案:

答案 0 :(得分:5)

首先收集约束,然后应用or_

constraints = []
if 'column1' in data:
    try:
        value = int(data['column1'])
    except (TypeError, ValueError):
        pass
    else:
        constraints.append(MyModel.column1 == value)

if 'column2' in data:
    try:
        value = datetime.utcfromtimestamp(int(data['column2']))
    except (TypeError, ValueError):
        pass
    else:
        constraints.append(MyModel.column2 >= value)

if constraints:
    query = query.filter(or_(*constraints))