Zack
Zack

Reputation: 57

How to Sum all instances of a model in Django

these are my models

class Countries(models.Model):
    Name = models.CharField(max_length=100)
    Language = models.IntegerField()
    Population = models.IntegerField(default=0)

class World(models.Model):
    Languages_spoken = model.Charfield(max_length=12000)
    World_population = models.IntegerField(default=0)

I am trying to add Population of all instances in Countries to sum and show on World_population field on class World

What I have tried

class World(models.Model):
    Languages_spoken = model.Charfield(max_length=12000)
    World_population = models.IntegerField(default=0)
    def save(self, *args, **kwargs):
        self.World_population = Countries.objects.get(Population) # I know this is not correct
        super(World,self).save()

Upvotes: 2

Views: 326

Answers (2)

Hasan
Hasan

Reputation: 968

You can use Sum() here,

self.World_population = Countries.objects.aggregate(Sum('Population'))

https://docs.djangoproject.com/en/2.1/topics/db/aggregation/

Upvotes: 1

10xprogrammer20x
10xprogrammer20x

Reputation: 66

Give this a shot:

from django.db.models import Sum
Countries.objects.aggregate(total_population=Sum('Population'))

More info on aggregation here

Upvotes: 4

Related Questions