Django - aggregation with get_FOO_display

◇◆丶佛笑我妖孽 提交于 2019-12-11 03:14:54

问题


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.


回答1:


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



回答2:


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

field = next(field for field in queryset.model._meta.fields
             if field.name == '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'))}


来源:https://stackoverflow.com/questions/25060594/django-aggregation-with-get-foo-display

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!