Django-使用get_FOO_display进行聚合 [英] Django - aggregation with get_FOO_display
问题描述
请考虑以下内容:
status = queryset.values('status').annotate(count=Count('status'))
其中 status
字段是一个 CharField
和选择
。这将产生具有 status
DB值及其计数的字典列表。
where status
field is a CharField
with choices
. This will result in a list of dictionaries with status
DB value along with its count.
有没有办法汇总状态
并显示其显示值?我已经查找了我可能可以模仿的 _get_FIELD_display
的代码,但是重复框架的内部代码有点。
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.
推荐答案
如果不对SQL进行黑客攻击,您可能无法轻松地在DB级别上实现这一目标。但是,由于 get_FOO_display
在 Model
级别上运行,您甚至不必黑客 _get_FIELD_display
或手动查找选项(如果以下方法不会使您的服务器花费太多):
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()
因此
for s in queryset.values('status').annotate(count=Count('status')):
print(queryset.model(status=s['status']).get_status_display())
这篇关于Django-使用get_FOO_display进行聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!