How to obtain months in right order from different years from DateField in django?

StackOverflow https://stackoverflow.com/questions/18416513

  •  26-06-2022
  •  | 
  •  

I have django model with DateField. I can get list of months of objects in such way:

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

and after delete duplicates I receive such list (example): [1, 2, 5, 6, 7, 9].

But if I have different years, I want to receive months in right date order. For example:

date1=31.08.2012, date2=31.12.2012, date3=05.05.2013.

So I want to receive not [5, 8, 12] but [8, 12, 5].

How can I do it?

有帮助吗?

解决方案

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!

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top