perf: avoid N+1 query in recent topics and news
This commit is contained in:
parent
8393cf1933
commit
13ce27b682
|
@ -16,13 +16,17 @@ def menu_processor():
|
|||
main_forum = Forum.query.filter_by(parent=None).first()
|
||||
|
||||
# Constructing last active topics
|
||||
raw = db.session.execute( """SELECT topic.id FROM topic
|
||||
rows = db.session.execute( """SELECT topic.id FROM topic
|
||||
INNER JOIN comment ON topic.thread_id = comment.thread_id
|
||||
INNER JOIN post ON post.id = comment.id
|
||||
GROUP BY topic.id
|
||||
ORDER BY MAX(post.date_created) DESC
|
||||
LIMIT 20;""")
|
||||
last_active_topics = [Topic.query.get(id) for id in raw]
|
||||
ids = [row[0] for row in rows]
|
||||
# Somewhat inelegant, but much better than loading individually
|
||||
recent_topics = db.session.query(Topic).filter(Topic.id.in_(ids)).all()
|
||||
recent_topics = sorted(recent_topics, key=lambda t: ids.index(t.id))
|
||||
|
||||
|
||||
# Filter the topics the user can view and limit to 10
|
||||
if current_user.is_authenticated:
|
||||
|
@ -30,10 +34,10 @@ def menu_processor():
|
|||
else:
|
||||
f = lambda t: t.forum.is_default_accessible()
|
||||
|
||||
last_active_topics = list(filter(f, last_active_topics))[:10]
|
||||
recent_topics = list(filter(f, recent_topics))[:10]
|
||||
|
||||
# Constructing last news
|
||||
raw = db.session.execute( """SELECT topic.id FROM topic
|
||||
rows = db.session.execute( """SELECT topic.id FROM topic
|
||||
INNER JOIN forum ON topic.forum_id = forum.id
|
||||
INNER JOIN comment ON topic.thread_id = comment.thread_id
|
||||
INNER JOIN post ON post.id = comment.id
|
||||
|
@ -42,8 +46,10 @@ def menu_processor():
|
|||
ORDER BY MIN(post.date_created) DESC
|
||||
LIMIT 10;
|
||||
""")
|
||||
last_news = [Topic.query.get(id) for id in raw]
|
||||
ids = [row[0] for row in rows]
|
||||
recent_news = db.session.query(Topic).filter(Topic.id.in_(ids)).all()
|
||||
recent_news = sorted(recent_news, key=lambda t: ids.index(t.id))
|
||||
|
||||
return dict(login_form=login_form, search_form=search_form,
|
||||
main_forum=main_forum, last_active_topics=last_active_topics,
|
||||
last_news=last_news)
|
||||
main_forum=main_forum, last_active_topics=recent_topics,
|
||||
last_news=recent_news)
|
||||
|
|
Loading…
Reference in New Issue