I have an XYZ model, and I need to get the maximum value for fields a, b and expression x / y for a given set of queries.
It works great for fields. Something like:
>>> XYZ.all().aggregate(Max('a')) ... {'a__max': 10}
However, I cannot find a way to do this for expressions. Try something like:
>>> XYZ.all().aggregate(Max('x/y'))
Gives an error:
*** FieldError: Cannot resolve keyword 'x/y' into field. Choices are: a, b, x, y, id
Try something like:
>>> XYZ.all().aggregate(Max(F('x')/F('y')))
Gives an error:
*** AttributeError: 'ExpressionNode' object has no attribute 'split'
And even something like:
XYZ.all().extra(select={'z':'x/y'}).aggregate(Max('z'))
Also does not work and gives the same error as above:
FieldError: Cannot resolve keyword 'z' into field. Choices are: a, b, x, y, id
One hack I found is:
XYZ.all().extra(select={'z':'MAX(x/y)'})[0].z
Actually, this works because it generates the correct SQL, but it is confusing because I get the correct value in z atttribute, but not in the correct instance, the one with the maximum value.
Of course, I could also use raw queries or tricks with optional () and order_by (), but it really doesn't make sense to me that Django fully supports aggregated queries, but can't support expressions even with its own F. expressions.
Is there any way to do this?