使用相关对象

使用相关对象


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

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

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

c1.invoices 的 invoices 属性将是一个空列表。我们可以将列表中的项目分配为 –

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

让我们使用 Session 对象将此对象提交到数据库,如下所示 –

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

这将自动为客户和发票表生成 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 的表视图中查看客户表和发票表的内容 –

客户表视图

发票表

您可以使用以下命令通过在构造函数本身中提供发票的映射属性来构造 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()

觉得文章有用?

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