问题
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