Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy - Writing a hybrid method for child count

I'm using Flask-SQLAlchemy, and I'm trying to write a hybrid method in a parent model that returns the number of children it has, so I can use it for filtering, sorting, etc. Here's some stripped down code of what I'm trying:

# parent.py
from program.extensions import db
from sqlalchemy.ext.hybrid import hybrid_method

class Parent(db.Model):
    __tablename__ = 'parents'
    parent_id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.String(80))
    children = db.relationship('Child', backref='parent', lazy='dynamic')

    def __init__(self, name):
        self.name = name

    @hybrid_method
    def child_count(self):
        return self.children.count()

    @child_count.expression
    def child_count(cls):
        return ?????

# child.py
from program.extensions import db
from program.models import Parent

class Child(db.Model):
    __tablename__ = 'children'
    child_id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey(Parent.parent_id))

    name = db.Column(db.String(80))
    time = db.Column(db.DateTime)

    def __init__(self, name, time):
        self.name = name
        self.time = time

I'm running into two problems here. For one, I don't know what exactly to return in the "child_count(cls)", which has to be an SQL expression... I think it should be something like

return select([func.count('*'), from_obj=Child).where(Child.parent_id==cls.parent_id).label('Child count')

but I'm not sure. Another issue I have is that I can't import the Child class from parent.py, so I couldn't use that code anyway. Is there any way to use a string for this? For example,

select([func.count('*'), from_obj='children').where('children.parent_id==parents.parent_id').label('Child count')

Eventually, I'll want to change the method to something like:

def child_count(cls, start_time, end_time):
    # return the number of children whose "date" parameter is between start_time and end_time

...but for now, I'm just trying to get this to work. Huge thanks to whoever can help me with this, as I've been trying to figure this out for a long time now.

like image 683
fimbul Avatar asked Nov 30 '12 06:11

fimbul


1 Answers

The code below shows it all.

class Parent(Base):
    __tablename__ = 'parents'
    # ...

    @hybrid_property
    def child_count(self):
        #return len(self.children)   # @note: use when non-dynamic relationship
        return self.children.count()# @note: use when dynamic relationship

    @child_count.expression
    def child_count(cls):
        return (select([func.count(Child.child_id)]).
                where(Child.parent_id == cls.parent_id).
                label("child_count")
                )

    @hybrid_method
    def child_count_ex(self, stime, etime):
        return len([_child for _child in self.children
            if stime <= _child.time <= etime ])

    @child_count_ex.expression
    def child_count_ex(cls, stime, etime):
        return (select([func.count(Child.child_id)]).
                where(Child.parent_id == cls.parent_id).
                where(Child.time >= stime).
                where(Child.time <= etime).
                label("child_count")
                )


# usage of expressions:
stime, etime = datetime.datetime(2012, 1, 1), datetime.datetime(2012, 1, 31)
qry = session.query(Parent)
#qry = qry.filter(Parent.child_count > 2)
qry = qry.filter(Parent.child_count_ex(stime, etime) > 0)
like image 76
van Avatar answered Nov 07 '22 23:11

van