Search code examples
djangodjango-ormdjango-aggregation

Django - aggregation with get_FOO_display


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.


Solution

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