与相关对象协同



在本章中,我们将重点关注 SQLAlchemy ORM 中的相关对象。

现在,当我们创建一个 Customer 对象时,一个空白的发票集合将以 Python 列表的形式存在。

c1 = Customer(name = "Gopal Krishna", address = "Bank Street Hydarebad", email = "[email protected]")

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', '[email protected]')
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 = "[email protected]",
      invoices = [Invoice(invno = 3, amount = 10000), 
      Invoice(invno = 4, amount = 5000)]
   )
]

或者使用会话对象的 add_all() 函数添加要添加的对象列表,如下所示 −

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

   Customer(
      name = "Abdul Rahman", 
      address = "Rohtak", 
      email = "[email protected]",
      invoices = [Invoice(invno = 9, amount = 15000), 
      Invoice(invno = 11, amount = 6000)
   ])
]

session.add_all(rows)
session.commit()
广告