【问题标题】:How do I write a Hybrid Property that depends on a column in children relationship?如何编写依赖于子关系列的混合属性?
【发布时间】:2015-10-22 15:50:12
【问题描述】:

假设我有两个表(使用 SQLAlchemy)供父母和孩子使用:

class Child(Base):
     __tablename__ = 'Child'
     id = Column(Integer, primary_key=True) 
     is_boy = Column(Boolean, default=False)
     parent_id = Column(Integer, ForeignKey('Parent.id'))


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

如何查询属性以了解父母是否有男孩的孩子?希望在 pandas 中使用此列,但不知道如何有效地查询它。我的直觉是创建一个 SQLALchemy 混合属性 has_a_boy_child,但我不确定如何定义混合属性或匹配表达式。谢谢!

【问题讨论】:

    标签: python sql sqlalchemy


    【解决方案1】:

    Correlated Subquery Relationship Hybrid 为例,我将构建一个返回count 男孩的属性:

    @hybrid_property
    def has_a_boy_child(self):
        return any(child.is_boy for child in self.children)
    
    @has_a_boy_child.expression
    def has_a_boy_child(cls):
        return (
            select([func.count(Child.id)])
            .where(Child.parent_id == cls.id)
            .where(Child.is_boy == True)
            .label("number_of_boy_children")
        )
    

    你可以像这样使用它:

    q_has_boys = session.query(Parent).filter(Parent.has_a_boy_child).all()
    q_no_boys = session.query(Parent).filter(~Parent.has_a_boy_child).all()
    q_attr = session.query(Parent, Parent.has_a_boy_child).all()
    

    更新:如果你真的想要bool 而不是count(其中None 在pandas 中是na),你可以如下所示:

    @has_a_boy_child.expression
    def has_a_boy_child(cls):
        return (
            select([
                case([(exists().where(and_(
                    Child.parent_id == cls.id,
                    Child.is_boy == True,
                )).correlate(cls), True)],
                    else_=False,
                ).label("has_boys")
            ])
            .label("number_of_boy_children")
        )
    

    【讨论】:

    • 非常感谢!有没有办法让它返回一个布尔而不是计数?
    猜你喜欢
    • 2011-07-20
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 2013-09-25
    • 2013-08-04
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多