V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
ossicee
V2EX  ›  Python

请教各位一个关于 Flask-sqlalchemy group_by 的问题

  •  
  •   ossicee · 2017-05-31 21:53:08 +08:00 · 4900 次点击
    这是一个创建于 2514 天前的主题,其中的信息可能已经有所发展或是发生改变。

    各位大神,菜鸟一枚 我有一个文章表 模型是

    class Post(db.Model):
        __tablename__ = 'post'
    
        id = db.Column(db.Integer, primary_key=True)
        title = db.Column(db.String(32), unique=True)
        body = db.Column(db.Text)
        author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
        category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    

    有一个分类表 模型是

    class Category(db.Model):
        __tablename__ = 'category'
    
        id = db.Column(db.Integer, primary_key=True)
        posts = db.relationship('Post', backref='postcategory', lazy='dynamic')
        categoryName = db.Column(db.String(32), unique=True, index=True)
    

    我想查出category 文章分类每个分类有多少篇文章

    我有 sql 能查,语句是

    SELECT COUNT(id),(SELECT categoryName from category WHERE post.category_id=category.id) as N FROM post GROUP BY category_id
    

    请教一下各位大神,如果用 flask-sqlalchemy 怎么写呀 谢谢各位了

    5 条回复    2017-06-05 09:26:51 +08:00
    ossicee
        1
    ossicee  
    OP
       2017-06-01 09:26:27 +08:00 via Android
    💪
    fangzq
        2
    fangzq  
       2017-06-01 11:09:28 +08:00   ❤️ 1
    可以试试这个:

    ```python
    from sqlalchemy import func
    db.session.query(func.count(Post.id), Category.categoryName).select_from(Category).\
    join(Post, Category.id == Post.category_id).group_by(Post.category_id).all()
    ```
    ossicee
        3
    ossicee  
    OP
       2017-06-01 15:56:08 +08:00 via Android
    @fangzq 谢谢您,我等下回家测试一下,谢谢您帮助我
    ossicee
        4
    ossicee  
    OP
       2017-06-03 10:50:02 +08:00
    @fangzq 谢谢您,,。。原来我查资料,关键字全是 flask-sqlalchemy .原来用 sqlalchemy 就可以完成。谢谢您
    fangzq
        5
    fangzq  
       2017-06-05 09:26:51 +08:00
    解决了就好,不客气
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   987 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 22:12 · PVG 06:12 · LAX 15:12 · JFK 18:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.