使用相关对象
在本章中,我们将重点介绍 SQLAlchemy ORM 中的相关对象。
现在,当我们创建一个 Customer 对象时,一个空白的invoices集合将以 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()
这将自动为客户和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 的表视图中查看客户表和invoices表的内容 −
您可以使用以下命令在构造函数本身中提供invoices的映射属性来构造客户对象−
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()