【问题标题】:Filter rows in child table using parent table having one to many relationship sqlalchemy使用具有一对多关系sqlalchemy的父表过滤子表中的行
【发布时间】:2020-11-13 07:44:30
【问题描述】:

我有两个具有一对多关系的表。

我想找到类型为“abc”的所有子行

class Parent(base):
    __tablename__ = "parent"
    id = Column("id", String, primary_key=True)
    parent = relationship("Child", back_populates="child")


class Child(base):
    __tablename__ = "child"
    id = Column("id", Integer, primary_key=True)
    name = Column(String)
    tid = Column(String, ForeignKey("parent.id"))
    child = relationship(Tenant, back_populates="parent")
    type = Column(String)


return self.session.query(Parent.parent).filter_by(Parent.parent.type == "abc").all()

它给了我错误,因为与 Parent.parent 关联的 InstrumentedAttribute' 对象和 'Comparator' 对象都有一个属性 'type'

如果我这样做了

return self.session.query(Parent).filter(Parent.parent.any(Child.type == type)).all()

它也给了我所有其他类型的行

【问题讨论】:

    标签: python python-3.x sqlalchemy flask-sqlalchemy marshmallow-sqlalchemy


    【解决方案1】:

    这会做你想做的:

    from sqlalchemy.orm import contains_eager
    
    q = (session.query(Parent)
                .join(Child)
                .options(contains_eager(Parent.parent))
                .filter(Child.type == 'abc'))
    
    for p in q:
        print(p.id, [c.name for c in p.parent])
    

    contains_eager 函数告诉 sqlalchemy,只有查询中指定的引用集合的行应该被急切加载:在上面的示例中,只有 Child 实例具有 type 的 'abc'。

    链接的文档警告,仅返回相关集合的选择可能会导致问题:在设计应用程序时,值得阅读警告并牢记这一点。

    【讨论】:

      猜你喜欢
      • 2014-03-12
      • 1970-01-01
      • 2021-10-22
      • 2012-10-06
      • 1970-01-01
      • 2016-08-23
      • 2021-12-17
      • 2021-08-14
      • 1970-01-01
      相关资源
      最近更新 更多