Mercurial > public > sg101
comparison gpp/news/utils.py @ 399:24f1230f3ee3
Fixing #193; reduce news query counts by grabbing tags and comment counts in bulk. Increased news items per page from 5 to 10.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Sat, 26 Mar 2011 03:08:05 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
398:701730b2fcda | 399:24f1230f3ee3 |
---|---|
1 """ | |
2 Common utility/helper code for the news app. | |
3 | |
4 """ | |
5 from django.contrib.contenttypes.models import ContentType | |
6 | |
7 from comments.models import Comment | |
8 from tagging.models import TaggedItem | |
9 from news.models import Story | |
10 | |
11 | |
12 def attach_extra_attrs(stories): | |
13 """ | |
14 For each story in the input stories list, attach 2 new attributes: | |
15 tag_list and comment_count. The tags and comment count info is pulled from | |
16 the database in bulk. This saves database queries when lots of news | |
17 stories are displayed at once. For best results, use ".defer('tags')" | |
18 when retrieve the stories from the database. | |
19 | |
20 """ | |
21 stories_dict = dict((story.id, story) for story in stories) | |
22 story_ids = stories_dict.keys() | |
23 | |
24 # Get all the tags out in one query | |
25 ct = ContentType.objects.get_for_model(Story) | |
26 tagged_items = TaggedItem.objects.filter(content_type=ct, | |
27 object_id__in=story_ids).select_related('tag') | |
28 | |
29 for story in stories_dict.values(): | |
30 story.tag_list = [] | |
31 story.comment_count = 0 | |
32 | |
33 # attach tags | |
34 for item in tagged_items: | |
35 stories_dict[item.object_id].tag_list.append(item.tag.name) | |
36 | |
37 # Now get all the comment counts out in one fell swoop | |
38 | |
39 story_ids = Comment.objects.filter(content_type=ct, | |
40 object_id__in=story_ids).values_list('object_id', flat=True) | |
41 | |
42 # compute comment_count | |
43 for story_id in story_ids: | |
44 stories_dict[story_id].comment_count += 1 |