首页 > 解决方案 > 对于 SQLAlchemy 查询,如何添加过滤器 'not' 子句?

问题描述

我将flask-appbuilder与SQLAlchemy模型一起使用,我发现他们所有的数据模型过滤器都使用“和”关系。

我的意思是当烧瓶查询某些东西时,它会:

self.datamodel.filter_by(id='abt').filter_by(testz_pro='mytest')

但我想使用“或”关系:

像这样的sql:

select * from number where id='1232' or id ='34343' 

所以,我必须将“或”关系更改为“和”

所以,我的 sql 就像:

select * from number where not (id<>'1232' and id<>'34343') 

我只是不知道 SQLAlchemy 查询如何表达“不”。

你能给我举个例子吗?

标签: pythonsqlalchemyorm

解决方案


您需要为此使用filter方法,因为无法否定filter_by的关键字参数。

from sqlalchemy import and_, not_

session.query(MyModel).filter(not_(and_(MyModel.id='abt', MyModel.testz_pro='mytest')))

推荐阅读