分组后最多可添加一个注释 [英] Maximum of an annotation after a group by

查看:75
本文介绍了分组后最多可添加一个注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为每对(b,c)对计算 a_priority的最大值。

I would like to compute the maximum of "a_priority" for each group of (b, c) pairs.

a_priority是基于大小写/时间的注释将字符串映射到优先级值。

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

我收到以下错误:

KeyError: 'a_priority'

我相信 qs.values( b, c)会过滤掉我的注释 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.

我的Django版本在python 3上为1.10。

My django version is 1.10 on python 3.

推荐答案

您是否尝试过将 Case 表达式直接放入 Max 中? 自Django 1.8起

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

这篇关于分组后最多可添加一个注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆