changeset 117:a3633f39f3ce

Forums: pre-select all the user profiles when displaying a topic. As it was, the template was calling get_user_profile which was causing a db hit on every post in the topic.
author Brian Neal <bgneal@gmail.com>
date Fri, 23 Oct 2009 03:09:33 +0000
parents 19b64e8f02a2
children a20b2c492d55
files gpp/forums/views.py gpp/templates/forums/display_post.html
diffstat 2 files changed, 14 insertions(+), 3 deletions(-) [+]
line wrap: on
line diff
--- a/gpp/forums/views.py	Fri Oct 23 03:08:40 2009 +0000
+++ b/gpp/forums/views.py	Fri Oct 23 03:09:33 2009 +0000
@@ -27,6 +27,7 @@
 from forums.unread import get_forum_unread_status, get_topic_unread_status, \
         get_post_unread_status
 
+from bio.models import UserProfile
 #######################################################################
 
 TOPICS_PER_PAGE = 50
@@ -109,7 +110,6 @@
     topic.save()
 
     posts = topic.posts.select_related()
-    get_post_unread_status(topic, posts, request.user)
 
     paginator = create_post_paginator(posts)
     page_num = int(request.GET.get('page', 1))
@@ -117,6 +117,17 @@
         page = paginator.page(page_num)
     except InvalidPage:
         raise Http404
+    get_post_unread_status(topic, page.object_list, request.user)
+
+    # Attach user profiles to each post to avoid using get_user_profile() in
+    # the template.
+    users = set(post.user.id for post in page.object_list)
+
+    profiles = UserProfile.objects.filter(user__id__in=users).select_related()
+    user_profiles = dict((profile.user.id, profile) for profile in profiles)
+
+    for post in page.object_list:
+        post.user_profile = user_profiles[post.user.id]
 
     last_page = page_num == paginator.num_pages
 
--- a/gpp/templates/forums/display_post.html	Fri Oct 23 03:08:40 2009 +0000
+++ b/gpp/templates/forums/display_post.html	Fri Oct 23 03:09:33 2009 +0000
@@ -6,8 +6,8 @@
       <a href="{% url bio-view_profile username=post.user.username %}" title="View Profile for {{ post.user.username }}">{{ post.user.username }}</a><br />
       <a href="{% url bio-view_profile username=post.user.username %}">{% avatar post.user %}</a>
       Joined: {{ post.user.date_joined|date:"M d, Y" }}<br />
-      Posts: {{ post.user.get_profile.forum_post_count }}<br />
-      Location: {{ post.user.get_profile.location }}<br />
+      Posts: {{ post.user_profile.forum_post_count }}<br />
+      Location: {{ post.user_profile.location }}<br />
    </td>
    <td class="forum-post-body">
       <div class="forum-post-info quiet">