Django: How to get latest value from db
<p>So I want to get the latest result for a list of values from the database.</p>

<p>Example:</p>

<pre><code>Task
col1 col2
1   1
2   12
3   32
4   1
5   24
1   25
2   62
3   7
2   81
1   9       -&gt; last occurence for '1' in 'col1'
4   10      -&gt; last occurence for '4' in 'col1'
3   121
5   12      -&gt; last occurence for '5' in 'col1'
</code></pre>

<p>There's a list 'z' and I want to write query such a way that I get the latest results from the table 'Task' such that z exists in col1. Assuming 'z' is:</p>

<pre><code>z = [1, 4, 5]
</code></pre>

<p>I want the end result as:</p>

<pre><code>col1 col2
1   9
4   10
5   12
</code></pre>

<p>There are 2 solutions that I came up with. 
Solution1 is as follows:</p>

<pre><code>all_results = Task.objects.filter(col1__in=z)
results = dict()
for result in results:
    results[result.col1] = result
</code></pre>

<p>Solution2 is as follows:</p>

<pre><code>results = dict()
for x in z:
    results[x] = Task.objects.filter(col1=x).reverse()[0]
</code></pre>

<p>But I'm wondering if there's a way to combine both solutions together such that I only have to make one database call and get results for each distinct 'col1'.
Reason: My database is very big and currently I've implemented Solution2 which is making the entire process very slow. Solution1 is not feasible since there are multiple entries and 'results' dictionary is going to be very big and hence it'll be very time consuming.</p>

<p>You may achieve this result from within the QuerySet. Your ORM query will be:</p>

<pre><code>Task.objects.filter(col1__in=z).values('col1').annotate(latest_record=Max('col2'))
# where z = [1, 4, 5]
</code></pre>

python django django-models