python - 在 SQLAlchemy 中使用连词进行查询

标签 python sql sqlalchemy conjunctive-normal-form

我正在尝试获取字符串列表并基于列表中所有字符串的或组合进行查询。我想知道下面是否可以做这样的事情。

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/

相关文章:

python - subprocess.Popen 不断询问 ssh-copy-id 命令的密码

python asyncio - 运行时错误 : await wasn't used with future

MySQL-尝试按不同表中的两个不同列进行排序

mysql - sqlalchemy Pyramid 查询keyerror

mysql - 我应该在SqlAlchemy中使用relationship()吗?

python - 在 SqlAlchemy 中创建动态选择查询

python - 如何更改 AWS 中 API 授权方的错误消息?

python - 获取重叠匹配的开始和停止索引?

c# - Entity Framework 如何使用带有谓词函数的 LINQ 检索行?

java - 如何在 HQL 或 JPQL 中使用强制转换?