SQLAlchemy 中的条件过滤 [英] Conditionally Filtering in SQLAlchemy
问题描述
有没有办法有条件地将 filter
参数添加到 SQL Alchemy ORM 中的查询中?
Is there a way to conditionally add filter
arguments to a query in the SQL Alchemy ORM?
例如想象一下,我有以下内容:
For example imagine, I have the following:
q = session.query(X)
if a:
q.filter(X.y == 'a')
elif b:
q.filter(X.y == 'a', X.z == 'b')
elif c:
q.filter(X.y == 'a', X.p == 'd')
有没有办法说只是添加
X.z == 'b'
if b
无需在每个过滤器中读取 (X.y == 'a')
.
without having to readd (X.y == 'a')
in every filter.
看来我可以做到
q.filter(X.y == 'a').filter(X.y == 'b')
但这会改变正在执行的查询.
but this changes the query that is being performed.
推荐答案
尝试将您的查询收集到一个列表中,然后在调用 filter
时使用 *
运算符:
Try collecting your queries into a list, and then use the *
operator when you call filter
:
queries = [X.y == 'a']
if b:
queries.append(X.z == 'b')
q.filter(*queries)
顺便说一句,我不明白为什么你认为链接两个 filter
会改变你的查询,它对应于 Xy = a AND Xz = b
就像你一样使用 filter(Xy == 'a', Xz == 'b')
.
And BTW I don't understand why you think chaining two filter
s would change your query, it would correspond to X.y = a AND X.z = b
like when you use filter(X.y == 'a', X.z == 'b')
.
这篇关于SQLAlchemy 中的条件过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!