Search code examples
pythondjangodjango-1.4

Django: filter by aggregate


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.


Solution

  • 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.