我有一个接受 SQLAlchemy 模型实例的例程。它所做的一件事是查看子对象的数量。如果我通过 ORM 的 select() 函数加载模型并立即加载相关记录,则效果很好;但是,当我创建一个新对象时,保留它,然后将其传递给使用函数,因为我超出了会话范围,所以我收到一个 DetachedInstanceError 。如何禁用新持久实例上的行为?
示例代码:
class Base(DeclarativeBase):
pass
class Customer(Base):
__tablename__ = 'customers'
customer_id: str = Column(String(36), primary_key=True)
orders: Mapped['Order'] = relationship('Order', back_populates='customer')
class Order(Base):
__tablename__ = 'orders'
order_id: str = Column(String(36), primary_key=True)
customer_id: str = Column(String(36), ForeignKey('customers.customer_id'))
customer: Mapped['Customer'] = relationship('Customer', back_populates='orders')
customer = Customer()
print(customer.orders) # Works fine
session.add(customer)
print(customer.orders) # Uh-oh
禁用延迟加载:
orders: Mapped['Order'] = relationship('Order', back_populates='customer', lazy='noload')