0

我有一个清单:scope_list = ['prd1 rls1', ' prd1 rls1 rls3 rls2']

我想根据scope_listSQL 创建一个过滤器,如下所示:

(product=prd1 AND `release` in (rls1)) OR (product=prd1 AND release in (rls1 ,rls3, rls2))

知道值的数量会scope_list有所不同,而我以前不知道。这就是为什么我想从scope_list.

在 SQL Alchemy 中,我想我应该这样做:

session.query(my_table).filter(or_(and_(my_table.product==%s,mytable.release.in_(%s))) for element.split() in scope_list)

我刚刚开始学习 SQL Alchemy,任何帮助将不胜感激。

4

1 回答 1

7

两者or_and_都可以采用可变数量的位置参数,因此如果您构建一个列表,您可以将其作为位置参数传递给or_(*or_args).

# First I split each term in the scope list.
scope_list = [term.split() for term in scope_list]
# Then the query is built.
or_args = [and_(
    my_table.product == scope[0], 
    my_table.release.in_(scope[1:])) for scope in scope_list]
results = session.query(my_table).filter(or_(*or_args)).all()
于 2013-07-02T23:39:51.483 回答