2015-04-02 42 views
1

我試圖在使用註釋時顯示選項的顯示名稱,但我一直無法弄清楚。我有以下查詢:在使用註釋時顯示Django中選擇字段的名稱

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'}] 

但我想要的東西,顯示的選擇字段的名稱,而不是關鍵:

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

我嘗試get_what_display(正如關於此主題的文檔和其他stackoverflow答案中所述),但Django會引發錯誤。即下面似乎並沒有工作

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

'get_prop_display'是屬性而不是數據庫字段。所以你必須循環它並更新顯示值AFAIK。 – 2015-04-02 19:32:54

回答

2

,因爲它是前面所說的,get_FOO_display是一個實例方法,而不是東西,你可以在.values()使用。因此,我會用Pythonic的方式來完成你想要做的事情:

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

只是Django 1.10的小更新:'選擇=字典(Survey._meta.get_field('what')。flatchoices)' – mizhgun 2017-02-24 11:22:45

相關問題