加入收藏 | 设为首页 | 会员中心 | 我要投稿 商洛站长网 (https://www.0914zz.com/)- AI应用、CDN、边缘计算、云计算、物联网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-09-05 22:35:33 所属栏目:Python 来源:互联网
导读:假设父母和孩子有两张桌子(使用SQLAlchemy):class Child(Base): __tablename__ = Child id = Column(Integer, primary_key=True) is_boy = Column(Boolean, default=False) parent_id

假设父母和孩子有两张桌子(使用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")
    )

(编辑:商洛站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读