django create dates list from queryset
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/200开发者_如何学Go9 | ????
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']
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
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
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)
精彩评论