Django ORM for fetching latest record for specific ID
Question:
How do I write a django ORM to fetch the most recent records from the table for a specific id.
Example:
I have table(tr_data) data like:
id
trs(foreign key)
status
last_updated
1
301
3
2022-11-28 06:14:28
2
301
4
2022-11-28 06:15:28
3
302
3
2022-11-28 06:14:28
4
302
4
2022-11-28 06:15:28
5
302
2
2022-11-28 06:16:28
I want to have a queryset values that gives me trs id with its latest status.I have tried with aggragate and MAX but not getting the desired result.
Expecting ouput as :
[{"trs":301, "status":4},"trs":302,"status":2}]
Answers:
Possible duplicate
Django ORM: Group by and Max
You can achieve this by annotate and Max. In the tr_data model, add a related_name parameter to trs something like ‘tr_status’.
Write an orm:
latest_objs = TrData.objects.annotate(temp=Max('trs__tr_status__last_updated')).filter(last_updated).values('trs', 'status')
How do I write a django ORM to fetch the most recent records from the table for a specific id.
Example:
I have table(tr_data) data like:
id | trs(foreign key) | status | last_updated |
---|---|---|---|
1 | 301 | 3 | 2022-11-28 06:14:28 |
2 | 301 | 4 | 2022-11-28 06:15:28 |
3 | 302 | 3 | 2022-11-28 06:14:28 |
4 | 302 | 4 | 2022-11-28 06:15:28 |
5 | 302 | 2 | 2022-11-28 06:16:28 |
I want to have a queryset values that gives me trs id with its latest status.I have tried with aggragate and MAX but not getting the desired result.
Expecting ouput as :
[{"trs":301, "status":4},"trs":302,"status":2}]
Possible duplicate
Django ORM: Group by and Max
You can achieve this by annotate and Max. In the tr_data model, add a related_name parameter to trs something like ‘tr_status’.
Write an orm:
latest_objs = TrData.objects.annotate(temp=Max('trs__tr_status__last_updated')).filter(last_updated).values('trs', 'status')