filter for multiple record based on latest timestamp

190 Views Asked by At

I have the following table:

Record    Created         Name    Group
1         July 23, 2015   John    Group 1
2         July 21, 2015   April   Group 1
3         April 4, 2015   John    Group 1

How do you filter for the latest distinct record? In this example, I would expect to get record 1 and 3? My code:

Model.objects.filter(Group='Group 1').latest('Created') 

only grabs record 1.

1

There are 1 best solutions below

0
On

latest return an object (row) that is, well, "latest" based on specified field provided as argument. If you need several records (rows) then you need to get a QuerySet. Try:

YourModel.objects.filter(Group='Group 1').order_by('-Created')[:2]

this should give you rows 1 and 3 as you expect.