当前位置: 代码迷 >> python >> 如何编写依赖于子关系中的列的混合属性?
  详细解决方案

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

热度:100   发布时间:2023-06-13 16:54:46.0

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

在示例之后,我将构建一个返回男孩子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在大熊猫中是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")
    )
  相关解决方案