For future readers you can use annotate
instead of aggregate
if you need the record / other fields and not just the max value.
i.e equivalent to this sql query
SELECT
first_name,
last_name,
Max(height) max_height
FROM patients;
Now one problem is passing an aggregate function in annotate will trigger a group by
from django.db.models import Max
Patients.objects.values('height').annotate(max_height=Max('height'))
>>>
SELECT "patients"."height",
MAX("patients"."height") AS "max_height"
FROM "patients"
GROUP BY "patients"."height"
The workaround is to use the Func expression
from django.db.models F, Func
Patients.objects.annotate(max_height=Func(F('height'), function='Max'))\
.values('first_name', 'last_name', 'max_height')
>>>
SELECT "patients"."first_name",
"patients"."last_name",
Max("patients"."height") AS "max_height"
FROM "patients"
see this if you need to do this in a subquery