我有一个包含选项的模型字段:
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}
完成此任务的最简单方法是什么?