SQLAlchemy:禁用延迟加载,仅在join()上加载对象

时间:2018-12-31 12:01:09

标签: python sqlalchemy

我正在禁用SQLAlchemy上的延迟加载,因此从数据库获取记录时,默认情况下它不会加载所有对象。当您在查询中专门加入用户对象或例如访问 event.user 时,我试图仅从事件对象中加载用户对象。使用参数是否可以做到这一点,或者禁用延迟加载是一种不好的做法?

我已经尝试过noload(“ *”)了,但是最后它禁用了任何连接。 例如,我有以下模型,还有正在测试的查询。

# Event model
class Event(Base):
    __tablename__ = 'events'

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(50), nullable=False)
    amount = Column(Integer)

    _user_id = Column("user_id", Integer, ForeignKey("users.id"), nullable=False)
    user = relationship(User)

# Query - This fetches also the whole user object <-- I don't want such behavior
some_session.query(Event).all()

# Query - I would like to load the user object when I will use the join() if possible
some_session.query(Event).join(Event.user).all()

enter image description here

1 个答案:

答案 0 :(得分:1)

默认的relationship loading strategy是“延迟加载”,它可以按照您想要的方式工作;仅当触摸User对象的user属性时,相关的Event才会加载。在您的情况下,当您检查对象以将属性显示为方便树时,IDE便会对其进行触摸,从而触发获取。同样happens easily with custom __repr__() implementations,如果不小心的话。

如果您希望使用联接加载相关用户,请使用joined loading

some_session.query(Event).options(joinedload(Event.user)).all()

或者如果您希望基于同一查询中的User进行过滤,explicit join(s) and contains_eager()

some_session.query(Event).join(Event.user).options(contains_eager(Event.user)).all()