SqlAlchemy关系选择列

3

我正在尝试找到一种使用SQLAlchemy关系选择列的方法:

我有这两个表:

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    label = Column(String)
    children = relationship("Child", back_populates="parent")

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('public.parent.id'))
    parent = relationship("Parent", back_populates="children")

当我使用时

db.query( models.Parent).first()

我得到了包含子对象列表的父对象,正如我所期望的那样,但我想要做的是仅选择几列,例如:
db.query( models.Parent.id, models.Parent.children)

在这种情况下,它不起作用,我收到以下错误消息:
无法找到行中的列“Children”。
1个回答

2

您可以在load_only()函数中使用选项。

stmt = select(Parent)

results = await db.execute(
    stmt
    .options(load_only(Parent.id))
    .options(selectinload(Parent.children))
)

*如果你想挑选一些列,只需像这样附加load_only()

.options(selectinload(Parent.children).load_only(Child.id, Child.name))

是的,我测试了execute(),但是query()会起作用。

session.query(User).options(load_only(User.name, User.fullname))

另请参阅: https://docs.sqlalchemy.org/en/14/orm/loading_columns.html#sqlalchemy.orm.load_only


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接