我开发了带有标签支持的简单博客。实际上我想添加标签云功能,我需要计算博客中使用的每个标签。我的博客和标签模型如下所示:
class Blog(db.Model, ObservableModel):
__tablename__ = "blogs"
id = db.Column(db.Integer, db.Sequence('blog_id_seq'), primary_key=True)
title = db.Column(db.String(200), unique=True, nullable=True)
tags = relationship('Tag', secondary=tags_to_blogs_association_table)
class Post(db.Model, ObservableModel):
__tablename__ = "posts"
......................
blog = relationship('Blog', backref = db.backref('blogs', lazy='dynamic'))
tags = relationship('Tag', secondary=tags_to_posts_association_table)
class Tag(db.Model):
__tablename__ = "tags"
id = db.Column(db.Integer, db.Sequence('post_id_seq'), primary_key=True)
title = db.Column(db.String(30), unique=False, nullable=True)
我想收集成对的字典,只有一种方法是通过检索包含标签项的帖子tag_name : count
来迭代集合。Blog.tags
其实我不确定它是最好的(从性能的角度来看)解决方案,也许flask-sqlalchemy提供了连接功能?问题:如何使用 Flask-SQLAlchemy 查询在 Python 中实现,如下所示:
select
t.id,
t.title,
count(post_id)
from tags t
join tags_to_blogs b on t.id=b.tag_id
join tags_to_posts p on t.id=p.tag_id
group by (t.id)
having b.blog_id=1