- SQLAlchemy 教程
- SQLAlchemy - 主頁
- SQLAlchemy - 介紹
- SQLAlchemy 核心
- 表示式語言
- 連線到資料庫
- 建立表
- SQL 表示式
- 執行表示式
- 選擇行
- 使用文字 SQL
- 使用別名
- 使用 UPDATE 表示式
- 使用 DELETE 表示式
- 使用多表
- 使用多表更新
- 引數順序更新
- 多表刪除
- 使用聯接
- 使用合取
- 使用函式
- 使用集合操作
- SQLAlchemy ORM
- 宣告對映
- 建立會話
- 新增物件
- 使用查詢
- 更新物件
- 應用過濾器
- 過濾器運算子
- 返回列表和標量
- 文字 SQL
- 建立關係
- 使用相關物件
- 使用聯接
- 常見的關係運算子
- eager 載入
- 刪除相關物件
- 多對多關係
- 方言
- SQLAlchemy 實用資源
- SQLAlchemy - 快速指南
- SQLAlchemy - 實用資源
- SQLAlchemy - 討論
SQLAlchemy ORM - 應用過濾器
在本章中,我們將討論如何應用過濾器,以及某些過濾器操作及其程式碼。
使用 filter() 方法可以對 Query 物件表示的結果集施加某些條件。filter 方法的一般用法如下 −
session.query(class).filter(criteria)
在以下示例中,透過條件 (ID>2) 篩選了 SELECT 查詢對 Customers 表獲得的結果集 −
result = session.query(Customers).filter(Customers.id>2)
此語句將轉換為以下 SQL 表示式 −
SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE customers.id > ?
由於已將繫結引數 (?) 賦予 2,因此只會顯示 ID 列>2 的行。完整程式碼如下 −
from sqlalchemy import Column, Integer, String
from sqlalchemy import create_engine
engine = create_engine('sqlite:///sales.db', echo = True)
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Customers(Base):
__tablename__ = 'customers'
id = Column(Integer, primary_key = True)
name = Column(String)
address = Column(String)
email = Column(String)
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind = engine)
session = Session()
result = session.query(Customers).filter(Customers.id>2)
for row in result:
print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email)
Python 控制檯中顯示的輸出如下 −
ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com ID: 4 Name: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com
廣告