Reputation: 1121
I want to get all the latest values of unique entries of a column in a Table. For Example I have a table like this, which is called Test
|____id|____fk1|__created|
| 1| 1| Nov 5|
| 2| 1| Nov 2|
| 3| 1| Nov 1|
| 4| 2| Nov 4|
| 5| 3| Nov 9|
| 6| 3| Nov 7|
Now I want to get all the entries in the table with unique 'fk1' values but the row where the 'created' column has the latest date. I want Django to return the queryset of the following rows
|____id|____fk1|__created|
| 1| 1| Nov 5|
| 4| 2| Nov 4|
| 5| 3| Nov 9|
What is a efficient Django way to do this?
Upvotes: 1
Views: 782
Reputation: 3880
You can use .distinct(**fields) in your query for that
example:
YourModel.objects.order_by('created').distinct('fk1')
Upvotes: 1