How do I write a Hybrid Property that depends on a column in children relationship?

2024/9/25 5:33:56

Let's say I have two tables (using SQLAlchemy) for parents and children:

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")

How can I query a property for whether the parent has any child that is a boy? Hoping to use this column in pandas but not sure how to effectively query it. My intuition is to create a SQLALchemy hybrid property has_a_boy_child, but I am not sure how to define the hybrid property or the matching expression. Thanks!

Answer

Following Correlated Subquery Relationship Hybrid example, I would build a property which returns count of boy children:

@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"))

And you can use it like:

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()

Update: If you really would like a bool instead of count (where None would be na in pandas), you can do it as shown below:

@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"))
https://en.xdnf.cn/q/71615.html

Related Q&A

Python insert a line break in a string after character X

What is the python syntax to insert a line break after every occurrence of character "X" ? This below gave me a list object which has no split attribute error for myItem in myList.split…

How to use properly Tensorflow Dataset with batch?

I am new to Tensorflow and deep learning, and I am struggling with the Dataset class. I tried a lot of things and I can’t find a good solution. What I am trying I have a large amount of images (500k+)…

How to handle a huge stream of JSON dictionaries?

I have a file that contains a stream of JSON dictionaries like this:{"menu": "a"}{"c": []}{"d": [3, 2]}{"e": "}"}It also includes nested dict…

datatype for handling big numbers in pyspark

I am using spark with python.After uploading a csv file,I needed to parse a column in a csv file which has numbers that are 22 digits long. For parsing that column I used LongType() . I used map() func…

Multi processing code repeatedly runs

So I wish to create a process using the python multiprocessing module, I want it be part of a larger script. (I also want a lot of other things from it but right now I will settle for this)I copied the…

Why use os.setsid() in Python?

I know os.setsid() is to change the process(forked) group id to itself, but why we need it?I can see some answer from Google is: To keep the child process running while the parent process exit.But acc…

How to apply different aggregation functions to same column by using pandas Groupby

It is clear when doingdata.groupby([A,B]).mean()We get something multiindex by level A and B and one column with the mean of each grouphow could I have the count(), std() simultaneously ?so result loo…

Can not connect to an abstract unix socket in python

I have a server written in c++ which creates and binds to an abstract unix socket with a namespace address of "\0hidden". I also have a client which is written in c++ also and this client can…

Pandas display extra unnamed columns for an excel file

Im working on a project using pandas library, in which I need to read an Excel file which has following columns: invoiceid, locationid, timestamp, customerid, discount, tax,total, subtotal, productid, …

Modifying the weights and biases of a restored CNN model in TensorFlow

I have recently started using TensorFlow (TF), and I have come across a problem that I need some help with. Basically, Ive restored a pre-trained model, and I need to modify the weights and biases of o…