【问题标题】:SQLAlchemy many to many filter rows by number of childrenSQLAlchemy 多对多按子项数过滤行
【发布时间】:2016-03-14 22:00:58
【问题描述】:

检索具有多个子级的表(即多对多的一部分)中所有行的最佳方法是什么?我试过了:

session.query(Parent).filter(len(Parent.children)>1).all() 

但我收到错误“'InstrumentedAttribute' 类型的对象没有 len()”。我已经能够让所有至少有一个孩子的父母使用:

session.query(Parent).filter(Parent.children).all()

【问题讨论】:

    标签: python sql sqlalchemy many-to-many


    【解决方案1】:

    使用having()

    from sqlalchemy import func
    
    session.query(Parent).\
            join(Parent.children).\
            group_by(Parent).\
            having(func.count(Child.id) > 1)
    

    【讨论】:

      猜你喜欢
      • 2012-11-11
      • 2013-08-18
      • 2014-03-12
      • 1970-01-01
      • 2011-03-20
      • 2018-04-26
      • 1970-01-01
      • 2020-01-13
      • 2021-08-14
      相关资源
      最近更新 更多