Skip to content Skip to sidebar Skip to footer

Sqlalchemy Count Related

I have been using django's ORM and sqlalchemy has me beat a.t.m. I have this: recipie_voters = db.Table('recipie_voters', db.Column('user_id', db.Integer, db.ForeignKey('user.i

Solution 1:

I am not sure how to put this in the django context, but with declarative and usage of Hybrid Attributes, the code might look like below:

class Recipie(Base):
    __tablename__ = 'recipie'
    id = Column(Integer, primary_key=True)
    name = Column(String(255))

    voters = relationship("User", 
             secondary=recipie_voters,
             backref=backref("votes", lazy="dynamic",),
             )


    @hybrid_property
    def voters_count(self):
        return len(self.voters)

    @voters_count.expression
    def voters_count(cls):
        return (select([func.count(recipie_voters.c.user_id)]).
                where(recipie_voters.c.recipie_id == cls.id).
                label("voters_count")
                )


# get only those Recipies with over 100 votes    
qry = session.query(Recipie).filter(Recipie.voters_count >= 100)

Post a Comment for "Sqlalchemy Count Related"