Anonymous 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.

Comments (0)

Files changed (2)


 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 =
+        articles =
         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
+            for article in
                 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:


     context = {}
     if tag:
         tag = get_object_or_404(Tag, name__iexact=tag)
-        articles =
+        articles =
         template = 'articles/display_tag.html'
         context['tag'] = tag
         # listing articles in a given month and year
         year = int(year)
         month = int(month)
-        articles =, publish_date__month=month)
+        articles =, publish_date__month=month)
         template = 'articles/in_month.html'
         context['month'] = datetime(year, month, 1)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.