Maximum of an annotation after a group by

后端 未结 2 916
谎友^
谎友^ 2021-01-05 10:33

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 va

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-05 11:10

    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))
    

提交回复
热议问题