在SQLAlchemy中,可以使用Query对象来执行灵活查询。以下是一些示例代码,可以帮助你进行灵活查询:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# 创建数据库连接
engine = create_engine('postgresql://username:password@localhost/dbname')
Session = sessionmaker(bind=engine)
session = Session()
# 简单查询
results = session.query(User).filter(User.age > 20).all()
for result in results:
print(result.name, result.age)
from sqlalchemy import and_, or_
# 复杂查询
results = session.query(User).filter(or_(User.age < 18, and_(User.age > 20, User.gender == 'male'))).all()
for result in results:
print(result.name, result.age, result.gender)
# 排序查询
results = session.query(User).order_by(User.age.desc()).all()
for result in results:
print(result.name, result.age)
from sqlalchemy import join
# 多表查询
results = session.query(User, Address).join(Address).filter(Address.city == 'New York').all()
for user, address in results:
print(user.name, address.street)
通过结合以上方法,你可以实现各种不同的灵活查询需求。更多有关SQLAlchemy的查询方法和用法,请参考官方文档:https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.