Django - 分组数据并在模板中显示选项名称

Django - Grouping data and showing the choices's name in template

我正在尝试创建饼图 (chart.js)。我的目标是对职称进行分组并在饼图中按职称显示工作人数。

Models.py

class Personel(models.Model):
    name = models.CharField(max_length=30)
    surName = models.CharField(max_length=20)
    titles= models.IntegerField(choices=((1,"Researcher"),(2,"Technician"),(3, "Support Personel")),default=1)

    def __str__(self):
        return f"{self.name},{self.surName}"

    class Meta:
        db_table = "personel"
        verbose_name_plural = "Ar-Ge Personeller"


Views.py

def index(request):
    personel_titles = Personel.objects.values('titles').annotate(Count('titles'))
    context = {
        "personel_titles" : personel_titles,
    }
    return render(request, 'core/index.html',context)
>>> print(personel_titles)

>>> {'titles': 1, 'titles__count': 10}
{'titles': 2, 'titles__count': 11}
{'titles': 3, 'titles__count': 3}>

这对我来说没问题,我需要的就在这里。但我不知道如何在我的模板中显示标题名称(也在图表标签中)

模板

{% for title in personel_titles %}<p>{{ title.get_titles_display }}</p>{% endfor %}

我错过了什么?我如何 return 值中的选项名称?

这里您需要一点技巧,因为 Group By 表达式是在数据库级别执行的,而 get_FOO_display() 方法是在 python 级别执行的。

因此,在将值发送到模板之前,您需要将 display 值附加到上下文,如

def index(request):
    personel_titles = Personel.objects \
        .values('titles') \
        .annotate(Count('titles'))
    
    <b>for title in personel_titles:
        title["titles_display"] = Personel(titles=title["titles"]).get_titles_display()</b>

    context = {
        "personel_titles": personel_titles,
    }
    return render(request, 'core/index.html', context)

然后在您的模板中,

{% for title in personel_titles %}
    <b><p>{{ title.titles_display }} --- {{ title.titles__count }}</p></b>
{% endfor %}