B
B
bQ12019-08-06 16:03:02
Django
bQ1, 2019-08-06 16:03:02

QuerySet which returns an object with the maximum field value?

How to write a query to get an object with the maximum value of some field?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2019-08-06
@bQ1

max_object = SomeModel.objects.order_by('some_field').last()

or
max_object = (SomeModel.objects
                       .annotate(max_some=Max('some_field'))
                       .filter(some_field=F('max_some'))
                       .first())

A
Andrew, 2019-08-06
@deepblack

https://docs.djangoproject.com/en/dev/topics/db/ag...

>>> from django.db.models import Avg, Max, Min
>>> Book.objects.aggregate(Avg('price'), Max('price'), Min('price'))
{'price__avg': 34.35, 'price__max': Decimal('81.20'), 'price__min': Decimal('12.99')}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question