我正在尝试获取字符串列表并基于列表中所有字符串的或组合进行查询。我想知道下面是否可以做这样的事情。
def filters(self,filter_company = ["DPL"]):
print "TEST"
# Company Filter
company_conj = 1 ## Bitwise 1 with AND will not effect other AND bits
for c in filter_company:
company_conj = (company_conj) & (Exception.company == c) ## Create co
qrty_exceptions = session.query(Exception).filter(company_conj) ## Query by conjunction
所以基本上,我正在迭代列表中的每个项目,并尝试通过连接来建立连接。重点是我不知道列表中有多少项......但我想按逻辑将它们按位与在一起,以便它们全部形成合词。我最终收到以下错误:
类型错误:& 不支持的操作数类型:'int' 和 BinaryExpression
实际上,我的意思不是使用按位或符号来写这个...“|”但我想如果你能做到 AND 那么它也应该适用于 OR。
最佳答案
我认为下面的示例应该对您有所帮助:
from sqlalchemy import or_, and_
company_filters = ["Filter1", "Filter2"] # as many as you like
clauses = [(Exception.company == c) for c in company_filters]
q = session.query(Exception)
q = q.filter(and_(*clauses)) # or `or_(*clauses)`
关于python - 在 SQLAlchemy 中使用连词进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32014920/