Home > Blockchain >  How to group by and get latest record in group contain all of fields in Django?
How to group by and get latest record in group contain all of fields in Django?

Time:10-30

Imagine we have a table like this:

id name type created_at
1 James male 2022-03-02
2 Jane female 2022-04-02
3 Kirk male 2022-03-04
4 Sarah female 2022-04-04
5 Jason male 2022-03-05

And i want to group by type and just get latest records based on created_at.
So i tried this code and not bad:

result = User.objects.values('type').annotate(
            latest_date=Max('created_at'),
) 

When print the result i face to this:

<QuerySet [
{'type': 'male', 'latest_date': '2022-03-05'}, 
{'type': 'female', 'latest_date': '2022-04-04'}
]>

My question is: Where is other fields id and name? I expect to get:

<QuerySet [
{id: 5, name: 'Jason', 'type': 'male', 'latest_date': '2022-03-05'}, 
{id: 4, name: 'Sarah', 'type': 'female', 'latest_date': '2022-04-04'}
]>

CodePudding user response:

Use order_by with distinct

User.objects.order_by("type", "-created_at").distinct("type")

CodePudding user response:

this might help you

result = User.objects.values('type').annotate(
                latest_date=Max('created_at'),
    ).values('id','name','type','latest_date')
  • Related