本文介绍了Sqlalchemy:使用多个 filter() 调用生成 OR 子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 sqlalchemy 的新手,可以使用一些帮助.我正在尝试编写一个小应用程序,我必须为其动态更改选择语句.所以我做 s = select([files]),然后我添加过滤器 s = s.where(files.c.createtime.between(val1, val2)).这很好用,但只能使用 AND 连接.因此,当我想要使用 createtime(在 1.1.2009 和 1.2.2009 之间)或 createtime == 5.2.2009 的所有条目时,我遇到了我不知道如何实现这一点的问题具有不同的过滤器调用.由于程序逻辑,不可能使用 s= s.where(_or(files.c.createtime.between(val1, val2), files.c.createtime == DateTime('2009-02-01')))

I'm new to sqlalchemy and could use some help.I'm trying to write a small application for which i have to dynamically change a select-statement. So I do s = select([files]), and then i add filters by s = s.where(files.c.createtime.between(val1, val2)).This works great, but only with an AND-conjunction.So, when I want to have all entries with createtime (between 1.1.2009 and 1.2.2009) OR createtime == 5.2.2009, I got the problem that i don't know how to achieve this with different filter-calls. Because of the programs logic it's not possible to use s= s.where(_or(files.c.createtime.between(val1, val2), files.c.createtime == DateTime('2009-02-01')))

提前致谢,克里斯托夫

推荐答案

您可以从列表中动态构建或子句:

You can build or clauses dynamically from lists:

clauses = []
if cond1:
    clauses.append(files.c.createtime.between(val1, val2))
if cond2:
    clauses.append(files.c.createtime == DateTime('2009-02-01'))
if clauses:
    s = s.where(or_(*clauses))

这篇关于Sqlalchemy:使用多个 filter() 调用生成 OR 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 19:10