在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.