skip to Main Content

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

2

Answers


  1. Use order_by with distinct

    User.objects.order_by("type", "-created_at").distinct("type")
    
    Login or Signup to reply.
  2. this might help you

    result = User.objects.values('type').annotate(
                    latest_date=Max('created_at'),
        ).values('id','name','type','latest_date')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search