Django: filter by aggregate

1.5k views Asked by At

I am trying to filter by a value calculated using aggregates. Currently I am doing this:

max_val = some_queryset.aggregate(max_val=Max('some_prop'))['max_val']
some_queryset.filter(some_prop=max_val)

Is there a way I can use max_val to filter, all done in a single query?

Unfortunately I am using Django 1.4. and no, I cannot update it, it is simply not up to me.

2

There are 2 answers

0
Moses Koledoye On BEST ANSWER

You can annotate the new field and compare with values from the aggregated field using an F expression:

from django.db.models import F, Max

some_queryset.annotate(max_val=Max('some_prop')).filter(max_val=F('another_prop'))

Annotation and F expressions exist in Django 1.4.

1
sagarchalise On

I donot know if this works on django 1.4 but you need to use annotate if you need to further filter it.

some_queryset.annotate(max_val=Max('some_prop')).filter(max_val=max_val)

You may need to populate max_val from your aggregate query.