如何按计数查询Flask Sqlalchemy组

时间:2019-10-13 15:42:40

标签: python flask flask-sqlalchemy

我有一张桌子,我想问的是一个带有group_by和count的flask-sqlalchemy查询。我已经尝试过SQL查询

SELECT COUNT(post_id), post_id FROM pageview WHERE date_posted BETWEEN '2019-10-01' AND '2019-10-14' GROUP BY post_id ORDER BY COUNT(post_id) DESC;

如何将以上查询转换为sqlalchemy查询? 我将以下内容附加到表类中

class Pageview(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, index=True, default=datetime.utcnow)

1 个答案:

答案 0 :(得分:1)

使用sqlaclhemy中的funccount

获取导入:

from sqlalchemy import *
from sqlalchemy.orm.session import sessionmaker

基于您的数据库获取会话-这是一个MySQL示例:

def obtain_session():
    """ Get SQLAlchemy session """
    engine = create_engine('mysql+mysqlconnector://username:password@mysql:3306/mydb')
    session = sessionmaker()
    # Bind the sessionmaker to engine
    session.configure(bind=engine)
    return session()

在您的函数或方法中,实现实际的查询-这将是这样的:

sess = obtain_session()
records = sess.query(Pageview.post_id,
                     func.count(Pageview.post_id).label('count')).
                     filter(Pageview.date_posted.between('2019-10-01', '2019-10-14')).
                     group_by(Pageview.post_id).order_by('count').desc()