0

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

2 Answers2

1

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}]}

Zkh
  • 490
  • 1
  • 4
  • 16
0

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

reference: Django regroup tag

Hashem
  • 595
  • 1
  • 3
  • 8
  • yep, but when na pass {% regroup notificacoes by date as criados_list %}. It returns a datetime, but i only want the year... i try date.year but doesn't work – Lucas Medeiros Oct 26 '22 at 13:02
  • are you tried to add date filter in template? like this your_date|date:"Y-m-d" – Hashem Oct 26 '22 at 13:14