【问题标题】:SQLAlchemy: Filter the Objects From Relationship When AccessedSQLAlchemy:在访问时从关系中过滤对象
【发布时间】:2020-12-11 04:45:56
【问题描述】:
  • 查询语句:获取名称以“A”开头的子项。将他们与父母联系起来。 架构:

  • 我有一对多的关系。 Parent(id, Name, children(rel->child)) -> Child(id, Name)

class Parent(Base):
    __tablename__ = 'parent'

    id = Column(Integer, primary_key=True)
    Name = Column(String)
    children = relationship("Child", lazy='joined')

class Child(Base):
    __tablename__ = 'child'

    id = Column(Integer, primary_key=True)
    Name = Column(String)

  • 想要过滤关系对象。 (即,当实例化 Parent.children 时获得的对象列表)。

  • 例如:[Parent(id=1, Name='Parent1' children=[Child(id='1', Name='AChild1'), Child(id='2', Name='Child2')] 需要在访问结果查询时过滤为:[Parent(id=1, Name='Parent1' children=[Child(id='1', Name='AChild1')]

如何编写语句来获得上述结果?

A solution that Filters them Once Loaded, I want to Filter them While Loading.

【问题讨论】:

标签: python sql python-3.x sqlalchemy


【解决方案1】:

也许我应该更努力地用谷歌搜索,但这是一些搜索的结果。

From SQLAlchemy Documentation:

当我们使用contains_eager() 时,我们正在自己构建将用于填充集合的 SQL。由此自然而然地,我们可以选择修改集合打算存储的值,方法是编写 SQL 来加载集合或标量属性的元素子集。

导致声明:

db.Query(Parent).join(Parent.children)\
                .filter(Parent.children.any(Child.Name.like("A%")))\
                .options(contains_eager(Parent.children))

【讨论】:

    猜你喜欢
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    相关资源
    最近更新 更多