Skip to content
Advertisement

django get record which is latest and other column value

I have a model with some columns, between them there are 2 columns: equipment_id (a CharField) and date_saved (a DateTimeField).
I have multiple rows with the same equipment_id and but different date_saved (each time the user saves the record I save the now date time).
I want to retrieve the record that has a specific equipment_id and is the latest saved, i.e.:
| Equipment_id | Date_saved |

| — —– | ——————— ——– |

| 1061a | 26-DEC-2020 10:10:23|
| 1061a | 26-DEC-2020 10:11:52|
| 1061a | 26-DEC-2020 10:22:03|
| 1061a | 26-DEC-2020 10:31:15|
| 1062a | 21-DEC-2020 10:11:52|
| 1062a | 25-DEC-2020 10:22:03|
| 1073a | 20-DEC-2020 10:31:15|
I want to retrieve for example the latest equipment_id=1061.
I have tried various approach without success:

prg = Program.objects.filter(equipment_id=id)  
program = Program.objects.latest('date_saved')
  

when I use program I get the latest record saved with no relation to the previous filter

Advertisement

Answer

You can chain the filtering as,

result = Program.objects.filter(equipment_id=id).latest('date_saved')
5 People found this is helpful
Advertisement