简体   繁体   English

如何在 sqlalchemy 中使用 sql NOT 运算符

[英]How to use sql NOT operator in sqlalchemy

I have a simple table with an int[] column and I would like to be able to select rows that do not contain a specified user.我有一个带有 int[] 列的简单表,我希望能够处理不包含指定用户的 select 行。 And I can't figure out how to do it with SQLAlchemy. I could easily make a request in SQL: SELECT * FROM practices WHERE not (33 = any(id_user)) but have no idea how to do it using Practice.query.filter(...)而且我不知道如何使用 SQLAlchemy 进行操作。我可以轻松地在 SQL 中发出请求: SELECT * FROM practices WHERE not (33 = any(id_user))但不知道如何使用Practice.query.filter(...)

Here is the schema for the table ("practices"):这是表的架构(“实践”):

Column        |          Type          |
--------------+------------------------+
 id           | integer                |
 some_data    | character varying(250) |
 id_user      | integer[]              |

Here is what it looks like with sample data:这是示例数据的样子:

 id |  some_data   |    id_user
----+--------------+---------------
  1 | ------       | {25,33,42,55}
  2 | ------       | {11,33,7,19}
  3 | ------       | {32,6,20,23}
  4 | ------       | {19,33,27,8}
  5 | ------       | {25,33,10,40}
  6 | ------       | {25,33,40,39}
  7 | ------       | {1,20,18,38}

After i run my query i want to see this:在我运行我的查询之后,我想看到这个:

id |  some_data   |    id_user
----+--------------+---------------
  3 | ------       | {32,6,20,23}
  7 | ------       | {1,20,18,38}

Here is the Python code I used to generate the table:这是我用来生成表格的 Python 代码:

class Practice(db.Model):
    __tablename__ = "practices"
    id = Column(Integer, primary_key=True)
    id_user = Column(ARRAY(Integer))
    some_data = Column(String(255))

    def __init__(self, id_user, some_data):
        self.id_user = id_user
        self.id_coach = id_coach
        self.id_coach = some_data

    def details(self):
        return {
            'id': self.id,
            'id_users': self.id_user,
            'some_data': self.some_data
        }

    def insert(self):
        db.session.add(self)
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    def update(self):
        db.session.commit()
query(Practice).filter(~Practice.id_user.contains([33])).all()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM