Home > other >  Group every objects by year
Group every objects by year

Time:10-27

I had 3 objects

[{u'criados': u'25/10/2022 00:50', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/9.pdf', u'id': 1, u'tipo': u'NAI', u'slug': u'Teste-1'}, {u'criados': u'25/10/2022 23:54', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/Profile.pdf', u'id': 2, u'tipo': u'NIP', u'slug': u'copa-06'}, {u'criados' : u'16/5/2020 21:25', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/test.pdf', u'id' : 3, u'tipo: u'NIP', u'slug': u'test-02'}]

this objects has different year and i want to display in html something like this:

2022
 - Object 1
 - Object 2

2020
 - Object 3

please help me

CodePudding user response:

You can achieve the grouping like this (You can still use the output in django template)

from datetime import datetime

x = [
    {
        'criados': '25/10/2022 00:50',
        'arquivo': 'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/9.pdf',
        'id': 1,
        'tipo': 'NAI',
        'slug': 'Teste-1'
    },
    ...
]


for obj in x:
    # create a key that holds the year value
    obj["year"] = datetime.strptime(
        obj['criados'], "%d/%m/%Y %H:%M").date().year

# group obj by key 'year'
newObj = {
    year: [obj for obj in x if obj["year"] == year] for year in sorted([y["year"] for y in x], reverse=True)
}

print(newObj)
// output
{2022: [{'criados': '25/10/2022 00:50', 'arquivo': 'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/9.pdf', 'id': 1, 'tipo': 'NAI', 'slug': 'Teste-1', 'year': 2022}, {'criados': '25/10/2022 23:54', 'arquivo': 'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/Profile.pdf', 'id': 2, 'tipo': 'NIP', 'slug': 'copa-06', 'year': 2022}], 2020: [{'criados': '16/5/2020 21:25', 'arquivo': 'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/test.pdf', 'id': 3, 'tipo': 'NIP', 'slug': 'test-02', 'year': 2020}]}

CodePudding user response:

if you want to group objects only in template, you can use {{regroup}} tag

reference: Django regroup tag

  • Related