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

Viewed 135

I am trying to create a pie chart (chart.js). My goal is grouping titles and displaying how many people work by title in piechart.

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}>

It is okay for me and all I need is in here. But I couldn't figure out how can I display title's name in my template(also in chart label)

Template

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

What am I missing? How can I return the choice's name in values?

1 Answers

You need a bit hack here since the Group By expression is performed on the Database level and the get_FOO_display() method performed on the python level.

So, before you sent the value to the template, you need to attach the display value to the context as,

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

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

and then in your template,

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