So I want to get the latest result for a list of values from the database.
Example:
Task
col1 col2
1 1
2 12
3 32
4 1
5 24
1 25
2 62
3 7
2 81
1 9 -> last occurence for '1' in 'col1'
4 10 -> last occurence for '4' in 'col1'
3 121
5 12 -> last occurence for '5' in 'col1'
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:
z = [1, 4, 5]
I want the end result as:
col1 col2
1 9
4 10
5 12
There are 2 solutions that I came up with. Solution1 is as follows:
all_results = Task.objects.filter(col1__in=z)
results = dict()
for result in results:
results[result.col1] = result
Solution2 is as follows:
results = dict()
for x in z:
results[x] = Task.objects.filter(col1=x).reverse()[0]
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.