或 SQL Alchemy 查询的多个过滤器
OR multiple filters for SQL Alchemy query
所以我正在尝试使用 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 两个过滤器都与我放入第二个过滤器查询的 or_ 无关。我需要更改什么才能创建正常工作的查询?
先收集约束,然后应用 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))
所以我正在尝试使用 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 两个过滤器都与我放入第二个过滤器查询的 or_ 无关。我需要更改什么才能创建正常工作的查询?
先收集约束,然后应用 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))