首页 > 解决方案 > 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}

完成此任务的最简单方法是什么?

标签: djangogroup-by

解决方案


我认为使用 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 中进一步处理,那似乎是最简单的。


推荐阅读