sqlalchemy计数相关 [英] sqlalchemy count related
本文介绍了sqlalchemy计数相关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在使用django的ORM,而sqlalchemy让我胜过了
我有这个:
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.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中选择选民(用户)的数量?
我们将从这里开始:
The question is: how can I select the count of voters (User) in Recipie?
We'll start from here:
Recipie.query.all()
推荐答案
我不确定如何将其放在django上下文中,但是使用了声明性和用法
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)
这篇关于sqlalchemy计数相关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文