Django query, finding the maximum object

Viewed 22

I'm hitting my head on something that should be simple.

I have a query like this:

MyModel.objects.filter(...).aggregate(max_value=Max('value'))

and this does, indeed, return a (dictionary) with key 'max_value' and value that maximum value.

But what I want is the object that has that maximum value. Or, at least, some subset of the fields of that object, but the max value is just the selector

1 Answers

You can work with the .latest(…) [Django-doc] to obtain the object with the maximum of certain field(s). This will internally order the queryset and then obtain the last object, so:

MyModel.objects.filter(…).latest('value')
Related