Django按“选择字段"和"COUNT个零"分组 [英] Django group by Choice Field and COUNT Zeros

查看:56
本文介绍了Django按“选择字段"和"COUNT个零"分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下Django模型:

consider the following django model:

class Image(models.Model):
image_filename = models.CharField(max_length=50)

class Rating(models.Model):
DIMENSIONS = [
    ('happy', 'happiness'),
    ('competence', 'competence'),
    ('warm_sincere', 'warm/sincere'),
]
rating_value = models.IntegerField(),
rating_dimension = models.CharField(max_length=50, choices=DIMENSIONS),
image = models.ForeignKey(Image, on_delete=models.CASCADE)

现在,我想像这样按类别对所有评分进行分组

Now, I'd like to group all Ratings by the number of ratings per category like this

Rating.objects.values("rating_dimension").annotate(num_ratings=Count("rating_value"))

返回如下查询集:

[{'rating_dimension': 'happy', 'num_ratings': 2},
 {'rating_dimension': 'competence', 'num_ratings': 5}]

有没有一种方法可以包含所有未评级的尺寸?实现类似

Is there a way to include all not-rated dimensions? To achieve an output like

[{'rating_dimension': 'happy', 'num_ratings': 2},
{'rating_dimension': 'competence', 'num_ratings': 5},
{'rating_dimension': 'warm_sincere', 'num_ratings': 0}] # ← zero occurrences should be included

提前谢谢!

推荐答案

首先,我们将创建一个字典,其中包含所有初始化为0的维的计数.

First we will create a dictionary with counts for all dimensions initialised to 0.

results = {dimension[0]: 0 for dimension in Rating.DIMENSIONS}

接下来,我们将查询数据库:

Next we will query the database:

queryset = Rating.objects.values("rating_dimension").annotate(num_ratings=Count("rating_value"))

接下来,我们将更新结果字典:

Next we will update our results dictionary:

for entry in queryset:
    results.update({entry['rating_dimension']: entry['num_ratings']})

在模板中,我们可以按 {%作为键,results.items%} 中的值对字典进行迭代.或者可以根据需要在视图中将字典转换为任何合适的结构.

In the template we can iterate over this dictionary by {% for key, value in results.items %}. Or the dictionary can be converted to any suitable structure as per need in the views.

这篇关于Django按“选择字段"和"COUNT个零"分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆