Reputation: 432
I'm wondering if there is any way to pass a list to a django queryset and limit to the max/min/latest/oldest value for each item in the list.
Basically something like this:
serial_list = [2231, 2232, 2233]
data_queryset = Data.objects.filter(serial__in=serial_list).latest()
I'm fully aware that the above code doesn't work. I'm just trying to illustrate a queryset that would return the .latest()
value for each object where the serial
is in serial_list
.
Upvotes: 2
Views: 2268
Reputation: 41987
You can iterate over the serial_list
, and for each one get the latest()
element from the queryset after querying the model. Here, using a dict comprehension to set each iterated item from serial_list
as key and relevant latest()
item on queryset as value:
serial_list = [2231, 2232, 2233]
{serial_: Data.objects.filter(serial=serial_).latest('date_field') \
for serial_ in serial_list}
Upvotes: 1