agdj/blog/archive.py
author Adam Gomaa <code@adam.gomaa.us>
Sun Feb 01 17:41:07 2009 -0500
changeset 425 94dad40a7a44
child 426 2a86d85cd508
permissions -rw-r--r--
Change the per-month archive URL.
     1 "Module to define some objects in for use in the archive pages"
     2 
     3 
     4 class Archive(object):
     5     "An archive for a queryset of objects"
     6     def __init__(self, queryset):
     7         "Build an Archive object out of the passed queryset"
     8         self.queryset = queryset
     9 
    10     def __iter__(self):
    11         return iter(self.years)
    12 
    13     @property
    14     def years(self):
    15         if not hasattr(self, "_years"):
    16             self.build_years()
    17         return sorted(self._years.values(), key=lambda y: -y.year)
    18 
    19     def build_years(self):
    20         self._years = {}
    21         for entry in self.queryset:
    22             year = entry.pub_date.year
    23             month = entry.pub_date.month
    24 
    25             if year not in self._years:
    26                 self._years[year] = Year(year)
    27             yearobj = self._years[year]
    28 
    29             if month not in yearobj.months:
    30                 yearobj.months[month] = Month(year, month)
    31             monthobj = yearobj.months[month]
    32 
    33             monthobj.entries.append(entry)
    34 
    35 
    36 class Year(object):
    37     def __init__(self, year):
    38         self.year = year
    39         self.months = {}
    40 
    41     def __unicode__(self):
    42         return unicode(self.year)
    43 
    44     def __iter__(self):
    45         return iter(sorted(self.months.values(), key=lambda m: m.month))
    46 
    47     @property
    48     def count(self):
    49         return sum([month.count for month in self])
    50 
    51 
    52 class Month(object):
    53     def __init__(self, year, month):
    54         self.year = year
    55         self.month = month
    56         self.entries = []
    57 
    58     @property
    59     def count(self):
    60         return len(self.entries)
    61 
    62     def __iter__(self):
    63         return iter(sorted(self.entries, key=lambda x: x.pub_date))
    64 
    65     def __unicode__(self):
    66         from datetime import date
    67         return "%s %s" % (date(2000, self.month, 1).strftime("%B"), unicode(self.year))
    68 
    69     @property
    70     def abbrev(self):
    71         from datetime import date
    72         return date(2000, self.month, 1).strftime("%b").lower()
    73 
    74     @property
    75     def url(self):
    76         from django.core.urlresolvers import reverse
    77 
    78         return reverse("blog-archive-month", args=[self.year, self.abbrev])
    79