Sqlalchemy:在不读取所有子项的情况下获取子项计数

npk*_*npk 6 python sqlalchemy

这是我的家长和孩子课程:

class Parent(Base):
    id = Column(...)
    ...

    children = relationship("Child", backref="parent", lazy="select")

class Child(Base):
    id = Column(...)
    parent_id = Column(...)
    active = Column(Boolean(), ...)
Run Code Online (Sandbox Code Playgroud)

children惰性加载技术背后的原因Parent是可能有大量的子级与父级相关联。

现在,我想获取父母的活跃孩子的数量作为混合属性。我尝试这样做的方法如下:

class Parent(Base):
    ...

    @hybrid_property
    def active_count(self):
        return len([child for child in self.children if child.active])

    @active_count.expression
    def active_count(cls):
        return (
            select(func.count(Child.id))
            .where(Child.parent_id == cls.id)
            .where(Child.active == True)
        )
Run Code Online (Sandbox Code Playgroud)

但此方法的问题是,当我调用 时parent.active_count,它会触发一个查询来获取所有子项。

我怎样才能只得到(活跃的孩子的)数量而不读取整个孩子的数量?

jor*_*zel 4

我认为您不必要在 Hybrid_property 定义中迭代子项active_count。这应该适合你:

class Parent(Base):
    ...
    children = relationship("Child", backref="parent", lazy="dynamic")

    @hybrid_property
    def active_count(self):
        return self.children.filter_by(active=True).with_entities(func.count('*')).scalar()
        # or 
        # return self.children.filter_by(active=True).count()
        # but it would have worse performance
Run Code Online (Sandbox Code Playgroud)