python – 如何编写依赖于子关系中的列的混合属性?

假设父母和孩子有两张桌子(使用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,但我不确定如何定义混合属性或匹配表达式.谢谢!

最佳答案
Correlated Subquery Relationship Hybrid示例之后,我将构建一个返回男孩子数的属性:

@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在大熊猫中是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")
    )

相关文章

使用OpenCV实现视频去抖 整体步骤: 设置输入输出视频 寻找帧...
前言 对中文标题使用余弦相似度算法和编辑距离相似度分析进行...
前言 之前尝试写过一个爬虫,那时对网页请求还不够熟练,用的...
前言 本文使用Python实现了PCA算法,并使用ORL人脸数据集进行...
前言 使用opencv对图像进行操作,要求:(1)定位银行票据的...
天气预报API 功能 从中国天气网抓取数据返回1-7天的天气数据...