In a django view I am filter out the content for each year to display it in a chart via a template. Currently I am doing the calculation for each year manual, but there has to be a better way to right the code so that it just filters the content by year without having to hardcode the years. Also in the chart template I am also hardcoding the year and was wondering that could be written without hardcoding.
content_count_2006 = ContentItem.objects.filter(timestamp__year=2006).count()
content_count_2007 = ContentItem.objects.filter(timestamp__year=2007).count()
content_count_2008 = ContentItem.objects.filter(timestamp__year=2008).count()
content_count_2009 = ContentItem.objects.filter(timestamp__year=2009).count()
content_count_2010 = ContentItem.objects.filter(timestamp__year=2010).count()
content_count_2011 = ContentItem.objects.filter(timestamp__year=2011).count()
content_per_year = [content_count_2006, content_count_2007, content_count_2008, content_count_2009, content_count_2010, content_count_2011]
{% chart VerticalBarStack content_per_year %}
{% axes type xy %}
{% axes label "2006" "2007" "2008" "2009" "2010" "2011" %}
{% color CCCCCC %}
{% endchart %}
You could use a list comprehension:
content_per_year = [ ContentItem.objects.filter(timestamp__year=y).count() \
for y in range(2006, 2012) ]