5

Consider the following:

status = queryset.values('status').annotate(count=Count('status'))

where status field is a CharField with choices. This will result in a list of dictionaries with status DB value along with its count.

Is there a way to aggregate status and show its display value instead? I have looked up the code of _get_FIELD_display which I probably can emulate, but it feels a tad hackish to repeat the framework's internal code.

Aziz Alfoudari
  • 5,193
  • 7
  • 37
  • 53

2 Answers2

5

Without hacking a SQL, you may not achieve this in DB level easily. But, since get_FOO_display operates on Model level, you don't even have to hack _get_FIELD_display or lookup in choices manually (If the following method does not cost your server too much):

YourModel(status=status).get_status_display()

Thus

for s in queryset.values('status').annotate(count=Count('status')):
    print(queryset.model(status=s['status']).get_status_display())
okm
  • 23,575
  • 5
  • 83
  • 90
1

Take a look at django.contrib.admin.util.display_for_field function. You have to find the field object:

field = queryset.model._meta.get_field('status')
        

Then you can use it as:

display_for_field(status, field)

Or, in your case:

{ unicode(display_for_field(t['status'], field)): t['count']
    for t in queryset.values('taxonomy').annotate(count=models.Count('taxonomy'))}
Guillaume Lebreton
  • 2,586
  • 16
  • 25
rczajka
  • 1,810
  • 14
  • 13
  • What is taxonomy indicating here? Why doesn't status belong in the values args, given that it is the column he is trying to group by? I'm interested in accomplishing this without an extra for loop. – Adam Starrh Aug 04 '16 at 11:23