📜  SQLAlchemy ORM-删除相关对象

📅  最后修改于: 2020-11-27 07:54:27             🧑  作者: Mango


在单个表上执行删除操作很容易。您要做的就是从会话中删除映射类的对象并提交操作。但是,对多个相关表的删除操作并不复杂。

在我们的sales.db数据库中,Customer和Invoice类通过一对多关系映射到customer和invoice表。我们将尝试删除客户对象并查看结果。

作为快速参考,下面是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的相关发票对象仍然存在。可以通过以下代码进行验证-

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类,添加包括级联配置在内的地址关系。

关系函数的层叠属性是用逗号分隔的层叠规则列表,该列表确定如何将会话操作从父级“级联”到子级。默认情况下,它为False,这意味着它是“保存更新,合并”。

可用的级联如下-

  • 保存更新
  • 合并
  • 清除
  • 删除
  • 删除孤儿
  • 刷新过期

通常使用的选项是“ all,delete-orphan”,表示在所有情况下相关对象应与父对象一起跟随,并在取消关联时被删除。

因此,重新声明的客户类别如下所示-

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,并查看其相关发票对象的数量-

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