sqlalchemy计数相关

时间:2012-11-14 12:22:40

标签: python sqlalchemy flask flask-sqlalchemy

我一直在使用django的ORM而且sqlalchemy让我击败了.t.m.
我有这个:

recipie_voters = db.Table('recipie_voters',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('recipie_id', db.Integer, db.ForeignKey('recipie.id'))
)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    ...

class Recipie(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    ...
    voters = db.relationship('User', secondary=recipie_voters, backref=db.backref('votes', lazy='dynamic'))
    ...

问题是:如何在Recipie中选择选民(用户)的数量?
我们将从这里开始:

Recipie.query.all()

1 个答案:

答案 0 :(得分:2)

我不知道如何将它放在django上下文中,但是使用Hybrid Attributes的声明和用法,代码可能如下所示:

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)