sqlalchemy not in
时间: 2024-05-13 14:13:33 浏览: 6
The "not in" clause in SQLAlchemy is used to filter out records that do not match a specific set of values. It is equivalent to the SQL "NOT IN" operator.
Here is an example:
```
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# create an engine to connect to the database
engine = create_engine('postgresql://user:password@host:port/dbname')
# create a session factory
Session = sessionmaker(bind=engine)
# create a declarative base
Base = declarative_base()
# define a model
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
# create the table in the database
Base.metadata.create_all(engine)
# create a session
session = Session()
# filter out users with age not in the set [20, 30, 40]
users = session.query(User).filter(User.age.notin_([20, 30, 40])).all()
# print the results
for user in users:
print(user.name, user.age)
```
In this example, we filter out users with age not in the set [20, 30, 40] using the `User.age.notin_` method. The resulting query will only return users whose age is not in this set.