One option you can try is to create a custom manager for your model that provides a way to pull out the archives. Here's code that I use:
from django.db import models, connection
import datetime
class EntryManager(models.Manager):
def get_archives(self, level=0):
query = """
SELECT
YEAR(`date_posted`) AS `year`,
MONTH(`date_posted`) AS `month`,
count(*) AS `num_entries`
FROM
`blog_entry`
WHERE
`date_posted` <= %s
GROUP BY
YEAR(`date_posted`),
MONTH(`date_posted`)
ORDER BY
`year` DESC,
`month` DESC
"""
months = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
cursor = connection.cursor()
cursor.execute(query, [datetime.datetime.now()])
return [{'year': row[0], 'month': row[1], 'month_name': months[int(row[1])-1], 'num_entries': row[2]} for row in cursor.fetchall()]
You'll of course need to attach it to the model with:
objects = EntryManager()
This returns a list of dictionaries that contains the year, the numerical month, the month name, and the number of entries. You call it as such:
archives = Entry.objects.get_archives()