Flask如何计算标签数量

2024-09-30 14:21:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我开发简单的博客与标签支持。实际上我想添加标签云功能,我需要得到每个标签在博客中使用的计数。 我的博客和标签模型看起来像:

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这样的对字典,只有一种方法是通过检索包含标记项的posts遍历Blog.tags集合。 实际上,我不确定它是否是最好的(从性能角度来看)解决方案,也许FlaskSQLAlchemy提供了连接函数? 问:如何使用Flask SQLAlchemy查询在Python中实现,如下所示:

^{pr2}$

Tags: idtruedbmodeltagtagscolumnblog
2条回答

试试这个:

query = db.session.query(Tag, db.count(Post.id))
query = query.filter(
    (tags_to_posts_association_table.tag_id == Tag.id) & \
    (tags_to_posts_association_table.post_id == Post.id)
)
query = query.group_by(Tag.id)

这将生成以下查询:

^{pr2}$

更干净的方法可以是这样的:

query = db.session.query(Tag, db.func.count(Post.id))
# This works but the preferred way is what's below it
#query = query.join(tags_to_posts_association_table, Post)
query = query.join(Post.tags)
query = query.group_by(Tag.id)

这将生成以下查询:

SELECT tags.id AS tags_id, tags.title AS tags_title, count(posts.id) AS count_1 
FROM tags INNER JOIN tags_to_posts ON tags.id = tags_to_posts.tag_id INNER JOIN posts ON posts.id = tags_to_posts.post_id GROUP BY tags.id

所有这些都会产生相同的结果,您可以像这样将它们连锁起来:

query = db.session.query(Tag.title, db.func.count(Post.id)).join(Post.tags).group_by(Tag.id)

# This will give you a dictionary with keys the tag titles, and values the count of each
# Because you can iterate over the query, which will give you the results
# Or you can use query.all() and use it as you prefer.
results = dict(query)

另外,我不确定它是db.func.count还是{}。无论如何,您可以始终from sqlalchemy import func并使用func.count。在

我会这样做(伪代码,不记得正确的炼金术语法,但你应该能够很容易地“转换”它)

tags = Tags.findAll()
for tag in tags:
    myDict[tag] = Post.find(tags=tag).count()

在和,你应该把myDict中的所有标签和它们的计数

相关问题 更多 >