简体   繁体   中英

Django calculate percentage for population pyramid

I have a data set with population by gender and age groups, 0-4 men population, 0-4 women population etc.

I tried calculate percantage in views.py but it didn't work well. so i want to it calculate one time in models.py and save it in my database.

class Pyramid(models.Model):
    city = models.CharField(max_length=15)
    year = models.IntegerField(default=0)

    men_population_0_4 = models.IntegerField(default=0)
    women_population_0_4 = models.IntegerField(default=0)

    men_population_5_9 = models.IntegerField(default=0)
    women_population_5_9 = models.IntegerField(default=0)

    .
    .
    .

    men_population_90_over = models.IntegerField(default=0)
    women_population_90_over = models.IntegerField(default=0)

    def __str__(self):
        return '%s %s' % (self.city, self.year)

so firstly i need calculate total men and women population then calculate percentage according to each of gender and age group in models.py and storage it to database.

views.py

def Pyramid(request):
dataset = models.Pyramid.objects.all()

datasett = models.Pyramid.objects.annotate(
    sum_men=(
            F('men_population_0_4') + F('men_population_5_9')
            + F('men_population_10_14') + F('men_population_15_19')
            + ...
            + F('men_population_90_over')
           ),
    men_population_0_4_perc=(100*F('men_population_0_4') / F('sum_men')),
    men_population_5_9_perc=(100*F('men_population_5_9') / F('sum_men')),
    ...
)

context = {
    'dataset': dataset,
    'datasett': datasett,
}
return render(request, 'pyramid.html', context)

pyramid.html

{% for item in datasett %}
    {{ item.sum_men }}
    {{ item.men_population_0_4_perc }}
    {{ item.men_population_5_9_perc }}
{% endfor %}

i tried below and it works

models.py

class Pyramid(models.Model):
city = models.CharField(max_length=15)
year = models.IntegerField(default=0)

men_population_0_4 = models.IntegerField(default=0)
women_population_0_4 = models.IntegerField(default=0)

men_population_5_9 = models.IntegerField(default=0)
women_population_5_9 = models.IntegerField(default=0)

.
.
.

men_population_90_over = models.IntegerField(default=0)
women_population_90_over = models.IntegerField(default=0)

men_population_sum = models.IntegerField(default=0)
women_population_sum = models.IntegerField(default=0)


def men_population_0_4_percentage(self):
    perc = self.men_population_0_4 * 100 / self.men_population_sum
    return perc

def women_population_0_4_percentage(self):
    perc = self.women_population_0_4 * 100 / self.women_population_sum
    return perc
.
.
.

def __str__(self):
    return '%s %s' % (self.city, self.year)

but this isn't save in database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM