'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. 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(...)
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:
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()
Solution 1:[1]
query(Practice).filter(~Practice.id_user.contains([33])).all()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
