各位大神,菜鸟一枚 我有一个文章表 模型是
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 怎么写呀 谢谢各位了
1
ossicee OP 💪
|
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() ``` |
4
ossicee OP @fangzq 谢谢您,,。。原来我查资料,关键字全是 flask-sqlalchemy .原来用 sqlalchemy 就可以完成。谢谢您
|
5
fangzq 2017-06-05 09:26:51 +08:00
解决了就好,不客气
|