0

I have a model with datetime field. I want to get a table with three columns as, year, month and number of items in time span. And I also want to order them from newest to oldest. What I want to get is something like this:

2011 August 4
2011 March 7 

How do you suggest I should do that?

Edit

I ended up doing something like this, I am not sure if it is best way to go though.

query_set = Post.objects.all()
years = query_set.dates("pub_date","year")
date_hierarchy = {}
for year in years:
    date_hierarchy[year] = {}
    months = query_set.filter(pub_date__year=year.year).dates("pub_date","month")
    for month in months:
        date_hierarchy[year][month] = query_set.filter(pub_date__year=month.year,pub_date__month=month.month).count()

Then, in template:

{% for year, month_dict in date_hierarchy.items %}
    {% for month,post_count in month_dict.items %}
        <li><a href="{% url arsiv_month month.year month.month %}">{{ month|date:"Y E" }} [{{ post_count }}]</a></li>
    {% endfor %}
{% endfor %}
yasar
  • 13,158
  • 28
  • 95
  • 160
  • Django and Python both let you split out dates into their parts, so maybe you don't actually need the 3 columns and could go with just the 1. What problem are you trying to solve? – Jordan Sep 06 '11 at 13:27
  • I have blog post, I am trying to create an archive part in homepage, where I will show month by month links, and in link texts, I will give how many post on that month in parentheses. – yasar Sep 06 '11 at 13:29

1 Answers1

0

take a look at the SQL's GROUP BY clause. django supports this. for example: Django annotate groupings by month (the second response in the question that I linked seems more portable than the accepted answer).

Community
  • 1
  • 1
akonsu
  • 28,824
  • 33
  • 119
  • 194
  • I am not trying to get date ordered models, I am trying to get, date ordered dates with item counts with them. I added some more information in original post. – yasar Sep 06 '11 at 14:36
  • The link you provided looks like the answer, however, I didn't understand a thing about it. – yasar Sep 06 '11 at 14:51