Django create a list of dates from a set of queries

I want to create a list of different month / year values ​​based on the date fields in my db. So, for example, in my table there is

id | date_added | Title

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

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

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

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

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

and this table is taken from the model article

how to create a list:

['June 2009', 'August 2009', 'September 2009', 'January 2010']
+3
source share
3 answers

Using a filter dates(), I decided to solve my problem at the end, although the two answers above gave me the results I wanted.

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

+3
source

, [' 2009', ' 2009', ' 2009', ' 2010'] . , -

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

. date , .

-

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

[EDIT]

"", . http://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct

+5

The way I did this was to map a function to format a date column over a set of queries. Something like that:

queryset = Article.objects.filter()
print map(lambda article: article.date_added.strftime('%B %Y'), queryset)
0
source

Source: https://habr.com/ru/post/1758183/


All Articles