Regis Santos
Regis Santos

Reputation: 3749

How to calculate percentage with facility in Django 1.7

How to calculate percentage in Django 1.7?

I need return

[{'gender': 'F', 'perc': 55.0%}, {'gender': 'M', 'perc': 45.0%}]

In this case, i try

from myproject.core.models import Person
from django.db.models import Count

g = Person.objects.values('gender').annotate(perc=Count('gender')).order_by('gender').values('gender', 'perc')
total_itens = Person.objects.count()

But not result, and i try

gender_m = Person.objects.filter(gender='M').count()
gender_f = Person.objects.filter(gender='F').count()
total_itens = Person.objects.count()

gender_m * 100 / total_itens
gender_f * 100 / total_itens

My question: how to return this in context and render in template?

In template i want use

{% for item in itens %}
    {{ item.gender }} - {{ item.value }}
{% endfor %}

And i use TemplateView (generic views)

Upvotes: 1

Views: 1609

Answers (1)

ZZY
ZZY

Reputation: 3937

You just need to override method get_context_data. And your first trial was almost there.

class MyView(TemplateView):
    template_name = 'template.html'

    def get_context_data(self, **kwargs):
        genders = Person.objects.values('gender').annotate(cnt=Count('gender')).order_by('gender')
        total_items = Person.objects.count()
        items = [
            {'gender': g['gender'], 'value': g['cnt'] * 100 / total_items} for g in genders
        ]
        return {'items': items}

Upvotes: 2

Related Questions