Home > database >  Python group a list of years, months to remove duplication of years
Python group a list of years, months to remove duplication of years

Time:06-21

I have a table that contains orders, in which contains the date column. I am getting back the aggregate of the years, and months from that column so that I can use that data in a filter on the front end.

I have managed to get this data back, however it is not formatted in the way I would like.

Python

years = purchase_orders.objects.filter(user_id=info.context.user.id).annotate(year=ExtractYear('date'), month=ExtractMonth('date'),).order_by().values_list('year', 'month').order_by('year', 'month').distinct()

Data Returned

<QuerySet [(2020, 3), (2021, 4), (2022, 1), (2022, 2), (2022, 3), (2022, 4), (2022, 5)]>

Ideal Format

<QuerySet [(2020, (3)), (2021, (4)), (2022, (1, 2, 3, 4, 5))]>

CodePudding user response:

You can work with the groupby(…) function [Python-doc] of the itertools module [Python-doc]:

from itertools import groupby
from operator import itemgetter

years = purchase_orders.objects.filter(
    user=info.context.user
).values(
    year=ExtractYear('date'),
    month=ExtractMonth('date')
).order_by('year', 'month').distinct()

years = [
    (y, [ym['month'] for ym in yms])
    for y, yms in groupby(years, itemgetter('year'))
]

We thus first fetch the data from the database, and then post-process this by constructing a list of 2-tuples where the first item contains the year, and the second is a list of months for that year.

  • Related