diff --git a/app/routes/forum/index.py b/app/routes/forum/index.py index dbdbdb8..023b881 100644 --- a/app/routes/forum/index.py +++ b/app/routes/forum/index.py @@ -80,4 +80,16 @@ def forum_page(f, page=1): topics = f.topics.order_by(Topic.date_created.desc()).paginate( page, Forum.TOPICS_PER_PAGE, True) - return render('/forum/forum.html', f=f, topics=topics, form=form) + # Count comments; this direct request avoids performing one request for + # each topic.thread.comments.count() in the view, which the database + # doesn't really appreciate performance-wise. + req_comment_counts = \ + "SELECT thread_id, COUNT(*) FROM comment WHERE " + \ + " OR ".join(f"thread_id={t.thread.id}" for t in topics.items) + \ + " GROUP BY thread_id" + + comment_counts = db.session.execute(req_comment_counts) + comment_counts = dict(list(comment_counts)) + + return render('/forum/forum.html', f=f, topics=topics, form=form, + comment_counts=comment_counts) diff --git a/app/templates/forum/forum.html b/app/templates/forum/forum.html index 932fa42..dbd5783 100644 --- a/app/templates/forum/forum.html +++ b/app/templates/forum/forum.html @@ -23,7 +23,7 @@ {{ t.title }} {{ t.author.name }} {{ t.date_created | date }} - {{ t.thread.comments.count() }} + {{ comment_counts[t.thread.id] }} {{ t.views }} {% endfor %}