annotate news/utils.py @ 943:cf9918328c64

Haystack tweaks for Django 1.7.7. I had to upgrade to Haystack 2.3.1 to get it to work with Django 1.7.7. I also had to update the Xapian backend. But I ran into problems. On my laptop anyway (Ubuntu 14.0.4), xapian gets mad when search terms are greater than 245 chars (or something) when indexing. So I created a custom field that would simply omit terms greater than 64 chars and used this field everywhere I previously used a CharField. Secondly, the custom search form was broken now. Something changed in the Xapian backend and exact searches stopped working. Fortunately the auto_query (which I was using originally and broke during an upgrade) started working again. So I cut the search form back over to doing an auto_query. I kept the form the same (3 fields) because I didn't want to change the form and I think it's better that way.
author Brian Neal <bgneal@gmail.com>
date Wed, 13 May 2015 20:25:07 -0500
parents ee87ea74d46b
children c6c3ba5cf6eb
rev   line source
bgneal@399 1 """
bgneal@399 2 Common utility/helper code for the news app.
bgneal@399 3
bgneal@399 4 """
bgneal@399 5 from django.contrib.contenttypes.models import ContentType
bgneal@399 6
bgneal@399 7 from comments.models import Comment
bgneal@399 8 from tagging.models import TaggedItem
bgneal@399 9 from news.models import Story
bgneal@399 10
bgneal@399 11
bgneal@399 12 def attach_extra_attrs(stories):
bgneal@399 13 """
bgneal@399 14 For each story in the input stories list, attach 2 new attributes:
bgneal@399 15 tag_list and comment_count. The tags and comment count info is pulled from
bgneal@399 16 the database in bulk. This saves database queries when lots of news
bgneal@399 17 stories are displayed at once. For best results, use ".defer('tags')"
bgneal@399 18 when retrieve the stories from the database.
bgneal@399 19
bgneal@399 20 """
bgneal@399 21 stories_dict = dict((story.id, story) for story in stories)
bgneal@399 22 story_ids = stories_dict.keys()
bgneal@399 23
bgneal@399 24 # Get all the tags out in one query
bgneal@399 25 ct = ContentType.objects.get_for_model(Story)
bgneal@399 26 tagged_items = TaggedItem.objects.filter(content_type=ct,
bgneal@399 27 object_id__in=story_ids).select_related('tag')
bgneal@399 28
bgneal@399 29 for story in stories_dict.values():
bgneal@399 30 story.tag_list = []
bgneal@399 31 story.comment_count = 0
bgneal@399 32
bgneal@399 33 # attach tags
bgneal@399 34 for item in tagged_items:
bgneal@399 35 stories_dict[item.object_id].tag_list.append(item.tag.name)
bgneal@399 36
bgneal@399 37 # Now get all the comment counts out in one fell swoop
bgneal@399 38
bgneal@399 39 story_ids = Comment.objects.filter(content_type=ct,
bgneal@399 40 object_id__in=story_ids).values_list('object_id', flat=True)
bgneal@399 41
bgneal@399 42 # compute comment_count
bgneal@399 43 for story_id in story_ids:
bgneal@399 44 stories_dict[story_id].comment_count += 1