简体   繁体   English

获取子列的平均值,但来自 SQLAlchemy 中过滤的父数据

[英]Get average of a child column, but from filtered parent data in SQLAlchemy

If I have a one-to-many relationship (where a parent can have many children) like so:如果我有一对多的关系(父母可以有很多孩子),像这样:

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

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    data = Column(Integer, nullable=False)
    parent = relationship("Parent", back_populates='children')

I want all children whose parents have 70 < score < 100 , and of those children, I want the average of all their data .我想要所有父母有70 < score < 100的孩子,在这些孩子中,我想要他们所有data的平均值。

I know I can get all the children with:我知道我可以让所有的孩子:

childs = session.query(Parent).filter(Parent.score > 70, Parent.score < 100)

for c in childs:
    # calculate the average 'data' here...

But this is probably not efficient and is very manual way of calculating the average child data.但这可能效率不高,并且是计算平均子数据的非常手动的方式。

I know there is this way of getting an average of a table:我知道有这种方法可以获取表格的平均值:

 session.query(func.avg(Child.data))

But how can I tie this into the above query where I filter on the parent's score?但是我怎样才能将它与上面过滤父母分数的查询联系起来呢?

我认为您可以应用与其他查询相同的过滤器:

 session.query(func.avg(Child.data)).filter(Child.parent.score > 70, Child.parent.score < 100)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM