使用注释时在Django中显示选择字段的名称 [英] Display name of a choice field in Django while using annotate

查看:67
本文介绍了使用注释时在Django中显示选择字段的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用注释时,我试图获取选项的显示名称,但我一直无法弄清楚。我有以下查询:

I am trying to get display names of choices when using annotate, but I haven't been able to figure out. I have the following query:

Survey.objects.values('what').annotate(count=Count('why')).order_by()

结果为:

[{'count': 34, 'what': u'a'}, 
{'count': 39, 'what': u'c'}, 
{'count': 40, 'wat': u'p'}]

但是我想要一些显示选择字段名称而不是键的东西:

But I want something that displays the name of the choice field and not the key:

[{'count': 34, 'what': u'appreciative'}, 
{'count': 39, 'what': u'creative'}, 
{'count': 40, 'wat': u'promising'}]

我尝试了get_what_display(如文档中提到的和该主题的其他stackoverflow答案中所述) ,但django引发错误。即以下内容似乎无效

I tried get_what_display (as mentioned on the docs and other stackoverflow answers on this topic), but django throws an error. i.e the following doesn't seem to work

Survey.objects.values('get_what_display').annotate(count=Count('why')).order_by()


推荐答案

前面说过, get_FOO_display 是一个实例方法,不是您可以在 .values()中使用的方法。因此,我将采用Python方式来完成您想做的事情:

As it's said earlier, get_FOO_display is an instance method, not something that you can use in .values(). Thus, I'd go with Pythonic way to accomplish what you'd like to do:

from django.utils.encoding import force_text

survey_counts = Survey.objects.values('what').annotate(count=Count('why')).order_by()

choices = dict(Survey._meta.get_field_by_name('what')[0].flatchoices)
for entry in survey_counts:
    entry['what'] = force_text(choices[entry['what']], strings_only=True)

这篇关于使用注释时在Django中显示选择字段的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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