Maximum of an annotation after a group by
django, python
Solution
Have you tried putting `Case` expression directly into `Max`? It is possible since Django 1.8.
from django.db.models import Max, Case, When, IntegerField
qs = MyObject.objects.all()
a_priority=Case(
When(a='A', then=1),
When(a='S', then=2),
When(a='Q', then=3),
output_field=IntegerField()
)
qs = qs.values("b", "c").annotate(max_a_priority=Max(a_priority))
Problem
I would like to compute the maximum of `a_priority` for each group of `(b, c)` pairs. `a_priority` is an annotation based on a case/when mapping strings to priority values. ``` from django.db.models import Max, Case, When, IntegerField qs = MyObject.objects.all() qs = qs.annotate( a_priority=Case( When(a='A', then=1), When(a='S', then=2), When(a='Q', then=3), output_field=IntegerField() ) ) qs = qs.values("b", "c").annotate(Max("a_priority")) ``` I get the following error: ``` KeyError: 'a_priority' ``` I believe the `qs.values("b", "c")` filters out my annotation `a_priority`. Behavior is different with any actual field, providing the max of the field. My django version is 1.10 on python 3.