I was trying to use an annotated value to filter a query set using an F
expression, but it turns out it it does not behave the way I am expecting.
I am trying to filter objects from a query set qs
whose property some_prop
is the maximum of that query set. For example:
set(qs.values_list('some_prop', flat=True))
would output:
set([1, 3, 5, 7, 9])
And I am aiming to filter qs
by the value 9, which is the maximum. I can easily achieve that using an aggregation:
max_prop = qs.aggregate(max_prop=Max('some_prop'))['max_prop']
qs.filter(some_prop=max_prop)
But I wanted to condense this behavior in a single query, so I used an annotation instead of an aggregation:
qs.annotate(max_prop=Max('some_prop')).filter(some_prop=F('max_prop'))
However this does not show the same behavior. This is actually just filtering by all some_prop
values rather than the maximum.
What am I missing? There must be something I am misunderstanding from the annotation and aggregation features.