SQLAlchemy ORM – 使用连接

SQLAlchemy ORM – 使用连接


现在我们有两个表,我们将看到如何同时在两个表上创建查询。为了在 Customer 和 Invoice 之间构建一个简单的隐式连接,我们可以使用 Query.filter() 将它们的相关列等同起来。下面,我们使用此方法一次加载 Customer 和 Invoice 实体 –

from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind = engine)
session = Session()

for c, i in session.query(Customer, Invoice).filter(Customer.id == Invoice.custid).all():
   print ("ID: {} Name: {} Invoice No: {} Amount: {}".format(c.id,c.name, i.invno, i.amount))

SQLAlchemy 发出的 SQL 表达式如下 –

SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email, invoices.id 
AS invoices_id, invoices.custid 
AS invoices_custid, invoices.invno 
AS invoices_invno, invoices.amount 
AS invoices_amount
FROM customers, invoices
WHERE customers.id = invoices.custid

以上代码行的结果如下 –

ID: 2 Name: Gopal Krishna Invoice No: 10 Amount: 15000
ID: 2 Name: Gopal Krishna Invoice No: 14 Amount: 3850
ID: 3 Name: Govind Pant Invoice No: 3 Amount: 10000
ID: 3 Name: Govind Pant Invoice No: 4 Amount: 5000
ID: 4 Name: Govind Kala Invoice No: 7 Amount: 12000
ID: 4 Name: Govind Kala Invoice No: 8 Amount: 8500
ID: 5 Name: Abdul Rahman Invoice No: 9 Amount: 15000
ID: 5 Name: Abdul Rahman Invoice No: 11 Amount: 6000

使用 Query.join() 方法可以轻松实现实际的 SQL JOIN 语法,如下所示 –

session.query(Customer).join(Invoice).filter(Invoice.amount == 8500).all()

join 的 SQL 表达式将显示在控制台上 –

SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email
FROM customers JOIN invoices ON customers.id = invoices.custid
WHERE invoices.amount = ?

我们可以使用 for 循环遍历结果 –

result = session.query(Customer).join(Invoice).filter(Invoice.amount == 8500)
for row in result:
   for inv in row.invoices:
      print (row.id, row.name, inv.invno, inv.amount)

使用 8500 作为绑定参数,显示以下输出 –

4 Govind Kala 8 8500  

Query.join() 知道如何在这些表之间进行连接,因为它们之间只有一个外键。如果没有外键或更多外键,Query.join() 在使用以下形式之一时效果更好 –

query.join(Invoice, id == Address.custid) 显式条件
query.join(Customer.invoices) 指定从左到右的关系
query.join(Invoice, Customer.invoices) 相同,有明确的目标
query.join(‘invoices’) 同样,使用字符串

类似地,可以使用 outerjoin() 函数来实现左外连接。

query.outerjoin(Customer.invoices)

subquery() 方法生成一个 SQL 表达式,表示嵌入在别名中的 SELECT 语句。

from sqlalchemy.sql import func

stmt = session.query(
   Invoice.custid, func.count('*').label('invoice_count')
).group_by(Invoice.custid).subquery()

stmt 对象将包含一个 SQL 语句,如下所示 –

SELECT invoices.custid, count(:count_1) AS invoice_count FROM invoices GROUP BY invoices.custid

一旦我们有了我们的语句,它的行为就像一个表结构。语句中的列可通过名为 c 的属性访问,如下面的代码所示 –

for u, count in session.query(Customer, stmt.c.invoice_count).outerjoin(stmt, Customer.id == stmt.c.custid).order_by(Customer.id):
   print(u.name, count)

上面的 for 循环显示发票的名称计数如下 –

Arjun Pandit None
Gopal Krishna 2
Govind Pant 2
Govind Kala 2
Abdul Rahman 2

觉得文章有用?

点个广告表达一下你的爱意吧 !😁