Reputation: 57
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
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
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