【问题标题】:How do I filter both parents and children in a O(1) queries?如何在 O(1) 查询中过滤父母和孩子?
【发布时间】:2013-09-01 07:48:12
【问题描述】:

我有一对具有基本父/子关系的模型。孩子有一个字段foo。我想做一个 SQLAlchemy 查询,该查询将返回所有具有 foo 匹配条件的子对象的 Parent 对象。与这些父母一起,我想返回孩子,但前提是他们符合过滤条件。

这些是我的模型:

class Parent(Model):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    children = relationship('Child', backref='parent')

class Child(Model):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    foo = Column(String(128))
    parent_id = Column(Integer, ForeignKey('parent.id'), nullable=False)

这是一个例子。假设我有父母AB。我有孩子a1a2b1b2。子 a1 具有 foo = 1a2.foo = 2 等等。

我想进行类似“child.foo == 1”的查询,并取回这些数据:

[
    {
        id: 'A',
        children: ['a1'],
    },
    {
        id: 'B',
        children: ['b1'],
    }
]

请注意,a2b2 不包含在结果中。

到目前为止我已经考虑过两个想法,但还没有实现:

  1. 选择子对象,然后构建父对象。

    执行此操作时,我无法查询父项上的字段,这也是必需的。

  2. 选择父母,然后遍历匹配的父母并进行更多查询以收集匹配的孩子。

    这(似乎)需要 O(n) 次查询,我不想这样做。

【问题讨论】:

    标签: python sql sqlalchemy


    【解决方案1】:

    要从单个查询中获得所需的一切,您需要使用 join()contains_eager()

    q = session.query(Parent).\
        join(Parent.children).\
        options(contains_eager(Parent.children)).\
        filter(Child.foo == 1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 2017-07-25
      • 1970-01-01
      相关资源
      最近更新 更多