SQLAlchemy ORM - 删除关联对象



在单个表上执行删除操作很容易。你所要做的就是从会话中删除映射类的对象并提交操作。但是,对多个相关表的删除操作有点棘手。

在我们的 sales.db 数据库中,Customer 和 Invoice 类分别映射到 customer 和 invoice 表,它们之间是一对多的关系。我们将尝试删除 Customer 对象并查看结果。

作为快速参考,以下是 Customer 和 Invoice 类的定义:

from sqlalchemy import create_engine, ForeignKey, Column, Integer, String
engine = create_engine('sqlite:///sales.db', echo = True)
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from sqlalchemy.orm import relationship
class Customer(Base):
   __tablename__ = 'customers'

   id = Column(Integer, primary_key = True)
   name = Column(String)
   address = Column(String)
   email = Column(String)
   
class Invoice(Base):
   __tablename__ = 'invoices'

   id = Column(Integer, primary_key = True)
   custid = Column(Integer, ForeignKey('customers.id'))
   invno = Column(Integer)
   amount = Column(Integer)
   customer = relationship("Customer", back_populates = "invoices")
   
Customer.invoices = relationship("Invoice", order_by = Invoice.id, back_populates = "customer")

我们设置了一个会话,并使用下面的程序通过主键 ID 查询获取一个 Customer 对象:

from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
x = session.query(Customer).get(2)

在我们的示例表中,x.name 恰好是 'Gopal Krishna'。让我们从会话中删除这个 x 并计算这个名称的出现次数。

session.delete(x)
session.query(Customer).filter_by(name = 'Gopal Krishna').count()

生成的 SQL 表达式将返回 0。

SELECT count(*) 
AS count_1
FROM (
   SELECT customers.id 
   AS customers_id, customers.name 
   AS customers_name, customers.address 
   AS customers_address, customers.email 
   AS customers_email
   FROM customers
   WHERE customers.name = ?) 
AS anon_1('Gopal Krishna',) 0

但是,x 的相关 Invoice 对象仍然存在。可以通过以下代码验证:

session.query(Invoice).filter(Invoice.invno.in_([10,14])).count()

这里,10 和 14 是属于 Gopal Krishna 客户的发票号码。上述查询的结果是 2,这意味着相关对象尚未被删除。

SELECT count(*) 
AS count_1
FROM (
   SELECT invoices.id 
   AS invoices_id, invoices.custid 
   AS invoices_custid, invoices.invno 
   AS invoices_invno, invoices.amount 
   AS invoices_amount
   FROM invoices
   WHERE invoices.invno IN (?, ?)) 
AS anon_1(10, 14) 2

这是因为 SQLAlchemy 并不假设级联删除;我们必须发出删除指令。

要更改此行为,我们需要在 User.addresses 关系上配置级联选项。让我们关闭当前会话,使用新的 declarative_base() 并重新声明 User 类,并在 addresses 关系中添加级联配置。

relationship 函数中的 cascade 属性是一个用逗号分隔的级联规则列表,它确定会话操作应如何从父级级联到子级。默认情况下,它是 False,这意味着它是“save-update, merge”。

可用的级联选项如下:

  • save-update
  • merge
  • expunge
  • delete
  • delete-orphan
  • refresh-expire

常用选项是 "all, delete-orphan",表示相关对象在所有情况下都应跟随父对象,并在取消关联时被删除。

因此,重新声明的 Customer 类如下所示:

class Customer(Base): 
   __tablename__ = 'customers'
   
   id = Column(Integer, primary_key = True) 
   name = Column(String) 
   address = Column(String) 
   email = Column(String) 
   invoices = relationship(
      "Invoice", 
      order_by = Invoice.id, 
      back_populates = "customer",
      cascade = "all, 
      delete, delete-orphan" 
   )

让我们使用下面的程序删除名为 Gopal Krishna 的 Customer,并查看其相关 Invoice 对象的数量:

from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind = engine)
session = Session()
x = session.query(Customer).get(2)
session.delete(x)
session.query(Customer).filter_by(name = 'Gopal Krishna').count()
session.query(Invoice).filter(Invoice.invno.in_([10,14])).count()

现在计数为 0,上面脚本发出的 SQL 如下:

SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email
FROM customers
WHERE customers.id = ?
(2,)
SELECT invoices.id 
AS invoices_id, invoices.custid 
AS invoices_custid, invoices.invno 
AS invoices_invno, invoices.amount
AS invoices_amount
FROM invoices
WHERE ? = invoices.custid 
ORDER BY invoices.id (2,)
DELETE FROM invoices 
WHERE invoices.id = ? ((1,), (2,))
DELETE FROM customers 
WHERE customers.id = ? (2,)
SELECT count(*) 
AS count_1
FROM (
   SELECT customers.id 
   AS customers_id, customers.name 
   AS customers_name, customers.address 
   AS customers_address, customers.email 
   AS customers_email
   FROM customers
   WHERE customers.name = ?) 
AS anon_1('Gopal Krishna',)
SELECT count(*) 
AS count_1
FROM (
   SELECT invoices.id 
   AS invoices_id, invoices.custid 
   AS invoices_custid, invoices.invno 
   AS invoices_invno, invoices.amount 
   AS invoices_amount
   FROM invoices
   WHERE invoices.invno IN (?, ?)) 
AS anon_1(10, 14)
0
广告