SQLAlchemy - Writing a hybrid method for child count

前端 未结 2 825
生来不讨喜
生来不讨喜 2020-12-09 04:06

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, e

相关标签:
2条回答
  • 2020-12-09 04:29

    I think you can just use plain ol' len and hybrid_property to get the count:

    @hybrid_property
    def child_count(self):
        return len(self.children)
    

    From the doc, that looks like it'd do the trick, unless I'm missing something?

    duggars = db.session.query(Parent).filter(Parent.child_count > 17)
    
    0 讨论(0)
  • 2020-12-09 04:32

    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)
    
    0 讨论(0)
提交回复
热议问题