0

Here is my data and code:

[
(datetime.date(2020, 3, 25), 'Raport'), 
(datetime.date(2020, 3, 24), 'Raport'), 
(datetime.date(2020, 3, 23), 'Raport'),

(datetime.date(2020, 3, 25), 'Document'), 
(datetime.date(2020, 3, 24), 'Document'), 
(datetime.date(2020, 3, 23), 'Document'),

(datetime.date(2020, 3, 25), 'Analize'), 
(datetime.date(2020, 3, 24), 'Analize'), 
(datetime.date(2020, 3, 23), 'Analize'),
]

Here is django (2.2) code:

sorted(DataSet.objects.values_list('doc_type', flat=True).distinct(), reverse=True)

I need to get the last and unique element of each document doc_type together with the date. At the moment I have the same list of documents:

['Raport', 'Document', 'Analize']

but I need:

[(datetime.date(2020, 3, 25), 'Raport'), (datetime.date(2020, 3, 25), 'Document'), (datetime.date(2020, 3, 25), 'Analize')]

Can someone provide me some hint? Thanks.

Webdev
  • 159
  • 1
  • 8

1 Answers1

1

If a Python solution fit your needs, use a dictionary to group and find the maximum:

import datetime

data = [
    (datetime.date(2020, 3, 25), 'Raport'),
    (datetime.date(2020, 3, 24), 'Raport'),
    (datetime.date(2020, 3, 23), 'Raport'),

    (datetime.date(2020, 3, 25), 'Document'),
    (datetime.date(2020, 3, 24), 'Document'),
    (datetime.date(2020, 3, 23), 'Document'),

    (datetime.date(2020, 3, 25), 'Analize'),
    (datetime.date(2020, 3, 24), 'Analize'),
    (datetime.date(2020, 3, 23), 'Analize'),
]

groups = {}

for date, group in data:
    if group not in groups:
        groups[group] = date
    elif date > groups[group]:
        groups[group] = date


result = [(v, k) for k, v in groups.items()]

print(result)

Output

[(datetime.date(2020, 3, 25), 'Raport'), (datetime.date(2020, 3, 25), 'Document'), (datetime.date(2020, 3, 25), 'Analize')]

This solution has O(n) time complexity.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
  • Thanks for your solution. I am gratefull. Please tell me if exists some django WuerySet methods to get the same results? – Webdev Mar 26 '20 at 16:34
  • I'm not sure if this can be done in a QuerySet method with SQLite as the DB engine – Dani Mesejo Mar 26 '20 at 16:40
  • OK, I will change it on Postgres but I would like to know also solution with djnago's methods – Webdev Mar 26 '20 at 16:42