Django 在 values_list 中检索 get_foo_value 并注释查询

Django retrieve get_foo_value within values_list and annotate query

我写了一个查询returns(评分,计数)

result = list(Film.objects.values_list('rating').annotate(count=Count('rating')))

rating 是

的选择字段
rating = (
        ("5","Excellent"),
        ("4","Good"),
        ("3","Average"),
        ("2","Bad"),
        ("1","Very Bad"),
    )

我目前得到的结果是这样的

[(5, 10), (4,8), (3,7), (2,1), (1,4)]

我希望得到这样的一对

[("Excellent",10),("Good",8)...]

我可以在查询中做些什么来获取它吗?获得所需结果的最佳方法是什么?

这里面有类似 get_foo_display 的东西。

我认为你可以CaseFunction实现下面的这个。

from django.db.models import Case, CharField, When
Film.objects.annotate(proxy_rating=Case(
    When(rating=5, then="Excellent"),
    When(rating=4, then="Good"),
    When(rating=3, then="Average"),
    When(rating=2, then="Bad"),
    When(rating=1, then="Very Bad"),
    output_field=CharField()     
    )).values_list("proxy_rating").annotate(count=Count('rating'))