不使用joinedload的SQLAlchemy[async]查询

0 投票
1 回答
37 浏览
提问于 2025-04-13 18:15
class Items(Base):
    tag_id = Column(Integer, ForeignKey(Tag.id, ondelete='CASCADE'), index=True)
    ...
    tag = relationship('Tag', back_populates='items')

query = Select(Items)
cursor = await db_session.execute(query)
items = cursor.scalars().all()
print(items[0].tag.id)  # 123

为什么不使用 joinedload 也能正常工作?那第二张表的额外查询是什么时候发生的呢?

1 个回答

0

这可能是因为这个 Tag 对象已经在会话缓存中了。

撰写回答