與相關物件協同



在本章中,我們將重點關注 SQLAlchemy ORM 中的相關物件。

現在,當我們建立一個 Customer 物件時,一個空白的發票集合將以 Python 列表的形式存在。

c1 = Customer(name = "Gopal Krishna", address = "Bank Street Hydarebad", email = "gk@gmail.com")

c1.invoices 的發票屬性將是一個空列表。我們可以像下面這樣向列表中分配項 −

c1.invoices = [Invoice(invno = 10, amount = 15000), Invoice(invno = 14, amount = 3850)]

讓我們使用會話物件將此物件提交到資料庫,如下所示 −

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

這將自動為 clients 和 invoices 表生成 INSERT 查詢 −

INSERT INTO customers (name, address, email) VALUES (?, ?, ?) 
('Gopal Krishna', 'Bank Street Hydarebad', 'gk@gmail.com')
INSERT INTO invoices (custid, invno, amount) VALUES (?, ?, ?)
(2, 10, 15000)
INSERT INTO invoices (custid, invno, amount) VALUES (?, ?, ?)
(2, 14, 3850)

現在,讓我們在 SQLiteStudio 的表檢視中檢視 clients 表和 invoices 表的內容 −

Customers Table View

Invoices Table

你可以透過使用以下命令在建構函式中提供發票的對映屬性來構造 Customer 物件 −

c2 = [
   Customer(
      name = "Govind Pant", 
      address = "Gulmandi Aurangabad",
      email = "gpant@gmail.com",
      invoices = [Invoice(invno = 3, amount = 10000), 
      Invoice(invno = 4, amount = 5000)]
   )
]

或者使用會話物件的 add_all() 函式新增要新增的物件列表,如下所示 −

rows = [
   Customer(
      name = "Govind Kala", 
      address = "Gulmandi Aurangabad", 
      email = "kala@gmail.com", 
      invoices = [Invoice(invno = 7, amount = 12000), Invoice(invno = 8, amount = 18500)]),

   Customer(
      name = "Abdul Rahman", 
      address = "Rohtak", 
      email = "abdulr@gmail.com",
      invoices = [Invoice(invno = 9, amount = 15000), 
      Invoice(invno = 11, amount = 6000)
   ])
]

session.add_all(rows)
session.commit()
廣告
© . All rights reserved.