Home > Software design >  How can I get latest record by queryset. like group by
How can I get latest record by queryset. like group by

Time:11-03

Data

name data1 data2 create_date
iron man ia ib 1630000000
hulk ha hb 1630000000
hulk hc hd 1630500000
captain ca cb 1630000000
captain cc cd 1630500000
captain ce cf 1630590000

I want to get latest data each name

name data1 data2 create_date
iron man ia ib 1630000000
hulk hc hd 1630500000
captain ce cf 1630590000

like this

wish_data = [
    {'name':'iron man', 'data1': 'ia', 'data2': 'ib', 'create_date':1630000000},
    {'name':'hulk', 'data1': 'hc', 'data2': 'hd', 'create_date':1630500000},
    {'name':'captain', 'data1': 'ce', 'data2': 'cf', 'create_date':1630590000},
]

I tried...

    Model.objects.filter(**conditions).values_list('name').annotate(cdate=Max('create_date'))
    
=> [('iron man', 1630000000), ('hulk', 1630500000), ('captain', 1630590000)]>

but i need to other columns...

Q

Is it possible with ORM? Or do I have to write the logic with for and if statements?

for example

wish_data = []
for name, data1, data2, create_date in Model.objects.filter(**conditions).values_list('name', data1, data2, 'create_date').order_by('-create_date'):
if name not in data:
    wish_data.append(
        {
            wish_data['name'] = name
            wish_data['data1'] = data1
            wish_data['data2'] = data2
            wish_data['create_date'] = create_date
        }
    )

CodePudding user response:

Yes, It is possible. You can make use of distinct and order_by together in your django orm query to get your wish_data. The query would be something like this:

distict_avengers = Model.objects.filter(**conditions).distinct("name").order_by("name", "-create_date").values("name", "data1", "data2", "create_date")

If you will print(distict_avengers) then you will see the following result:

[
  {"name": "captain", "data1": "ce", "data2": "cf", "create_date": 1630590000},
  {"name": "hulk", "data1": "hc", "data2": "hd", "create_date": 1630500000},
  {"name": "iron man", "data1": "ia", "data2": "ib", "create_date": 1630000000},
]

Please note that using distinct on fields is not supported on SQLite and also when using distinct and order_by together the fields mentioned in the order_by must always begin with the fields mentioned in the distinct.

  • Related