tags:

views:

32

answers:

3

I want to create a list of distinct month / year values based on a date fields in my db. So for example in my table I have

id | date_added | title

1 | 01/06/2010 | ????

2 | 02/09/2009 | ????

3 | 24/08/2009 | ????

4 | 15/06/2009 | ????

5 | 16/06/2009 | ????

and this table is from model article

how would I create a list of:

['June 2009', 'August 2009', 'September 2009', 'January 2010']
A: 

The way I would go about this would be to map a function to format the date column over the query set. Something like this:

queryset = Article.objects.filter()
print map(lambda article: article.date_added.strftime('%B %Y'), queryset)
Manoj Govindan
+3  A: 

I'm assuming that you need ['June 2009', 'August 2009', 'September 2009', 'January 2010'] for display purposes in your templates. If that is so, then you could do something like

Article.objects.values_list('date_added', flat=True)

which would give you a list of those dates. You could then use the date template filter to output what you want.

Something like

{% for item in your_dates_list_that_you_passed_to_the_template %}
    {{ item|date:"F Y" }}
{% endfor %}

[EDIT]

Regarding your requirement for "distinct", please see http://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct

chefsmart
+1. Given no additional information a template based solution would make more sense in the web framework context.
Manoj Govindan
+2  A: 

Using the dates() filter solved my problem in the end although the 2 answers above both gave me the results I wanted.

http://docs.djangoproject.com/en/dev/ref/models/querysets/#dates-field-kind-order-asc

John