Commits

codekoala  committed 3c3cad8

Code optimizations. I've managed to reduce the query count on some of the pages of my site considerably, just with these changes.

  • Participants
  • Parent commits 89247a2

Comments (0)

Files changed (2)

File articles/templatetags/article_tags.py

 from django import template
 from django.core.cache import cache
 from django.core.urlresolvers import resolve, reverse, Resolver404
+from django.db.models import Count
 from articles.models import Article, Tag
 from datetime import datetime
 import math
             order = 'publish_date'
 
         # get the active articles in the appropriate order
-        articles = Article.objects.active().order_by(order)
+        articles = Article.objects.active().order_by(order).select_related()
 
         if self.count:
             # if we have a number of articles to retrieve, pull the first of them
             archives = {}
 
             # iterate over all active articles
-            for article in Article.objects.active():
+            for article in Article.objects.active().select_related():
                 pub = article.publish_date
 
                 # see if we already have an article in this year
     tags = cache.get(cache_key)
     if tags is None:
         MAX_WEIGHT = 7
-        tags = Tag.objects.all()
+        tags = Tag.objects.annotate(count=Count('article'))
 
         if len(tags) == 0:
             # go no further
 
         min_count = max_count = tags[0].article_set.count()
         for tag in tags:
-            tag.count = tag.article_set.count()
             if tag.count < min_count:
                 min_count = tag.count
             if max_count < tag.count:

File articles/views.py

     context = {}
     if tag:
         tag = get_object_or_404(Tag, name__iexact=tag)
-        articles = tag.article_set.active()
+        articles = tag.article_set.active().select_related()
         template = 'articles/display_tag.html'
         context['tag'] = tag
 
         # listing articles in a given month and year
         year = int(year)
         month = int(month)
-        articles = Article.objects.active().filter(publish_date__year=year, publish_date__month=month)
+        articles = Article.objects.active().select_related().filter(publish_date__year=year, publish_date__month=month)
         template = 'articles/in_month.html'
         context['month'] = datetime(year, month, 1)