2

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.

2
  • That code does work, have you tried with a date field e.g.: Data.objects.filter(serial__in=serial_list).latest('date_field_name') ? Commented Jan 15, 2018 at 23:02
  • @heemayl that only returns a single object; The latest object in the queryset. I'm trying to get a latest object for each item in the list. So in this case, the queryset should have three objects. The latest for each serial in the list. Commented Jan 15, 2018 at 23:27

1 Answer 1

1

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}
Sign up to request clarification or add additional context in comments.

1 Comment

This works! I hadn't thought to use a dictionary like that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.