[Answered ]-How to obtain months in right order from different years from DateField in django?

2👍

You’re trying to get the months in order of when they first appear chronologically?

list(set(date.month for date in MyModel.objects.order_by("date").values_list('date', flat=True)))

Sorting by year is the same as sorting by date. Yay!

0👍

The only way to do it would be to add the year in too:

dates = [(i.year, i.month) for i in MyModel.objects.values_list('date', flat=True)]

That would return this list (once duplicates are removed and sorted):

[(2012, 8), (2012, 12), (2013, 5)]

If you wanted later, you could then get just the months by:

>>> [x[1] for x in dates]
[8, 12, 5]

But note that there may well be duplicates in that list too (August In both 2012 and 2013 would come out as 8, for example), and you wouldn’t necessarily know where the list changes from one year to the next.

👤Ben

Leave a comment