django - Django group by 添加不存在的选项
问题描述
我有一个包含选项的模型字段:
db_redirection_choices = (('A', 'first'), ('B', 'second'))
redirection_type = models.CharField(max_length=256, choices=db_redirection_choices, blank=True, null=True)
在某些时候,我正在对该列执行分组,计算所有现有选择:
results = stats.values('redirection_type').annotate(amount=Count('redirection_type')).order_by('redirection_type')
但是,这只会给我现有选择的结果。我想将那些甚至不存在的 0 添加到results
例如,如果表只包含条目
Id | redirection_type
--------------------------
1 | 'A'
那么annotate
只会返回
'A': 1
当然这很正常,但我仍然希望在结果中获得所有不存在的选择:
{'A': 1, 'B': 0}
完成此任务的最简单方法是什么?
解决方案
我认为使用 ORM 没有简单的方法,除了可能使用条件表达式,但我认为这会使您的查询更加复杂。
为什么不在 Python 中做一个简单的后处理?
db_redirection_choices = (('A', 'first'), ('B', 'second'))
# I think your queryset will have a similar shape
results = [{'redirection_type': 'A', 'amount': 1}]
results_map = {
**{choice: 0 for choice, _display in db_redirection_choices},
**{res['redirection_type']: res['amount'] for res in results}
}
assert results_map == {'A': 1, 'B': 0}
如果您不需要在 ORM 中进一步处理,那似乎是最简单的。
推荐阅读
- python - Python:如果用户没有手动滚动,则自动将 ScrolledText 滚动到末尾
- python - MongoDB - 向用户添加数据库和集合级别角色
- ruby - Ruby Selenium 自动测试警报窗口
- scala - 如何在 Apache Spark 2.3.1 中映射/转换 ArrayType 中的每个元素
- python - 修改字典键
- docker - 这个命令有什么作用?:`docker build . -f Dockerfile2 -t `
- spring-boot - 从 1.5.7 迁移到 Spring Boot 2 - 不支持请求方法 POST - csrf 已禁用
- swift3 - 如何使用 swift 3 滑动分页
- r - 与生成的统计数据不一致的 Kaplan-Meier 曲线图
- android - 使用 LocalDate 而不是日月年的 DatepickerDialog