“灯塔急切加载关系”这个术语可能不是一个广泛认可的标准术语,但从字面上理解,它可能指的是在某个系统或应用中,使用类似“灯塔”的机制来实现数据的急切加载(Eager Loading)。急切加载是一种数据加载策略,与延迟加载(Lazy Loading)相对。在急切加载中,相关的数据在主数据被访问时立即加载,而不是等到实际需要时才加载。
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
orders = relationship('Order', back_populates='user', lazy='joined') # 急切加载
class Order(Base):
__tablename__ = 'orders'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship('User', back_populates='orders')
engine = create_engine('sqlite:///example.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# 查询用户及其订单(急切加载)
user = session.query(User).options(joinedload(User.orders)).filter_by(id=1).first()
print(user.name)
for order in user.orders:
print(order.id)
领取专属 10元无门槛券
手把手带您无忧上云