如何在Django中汇总模型的所有实例

时间:2018-09-23 04:14:19

标签: python django django-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)

我正在尝试添加Population中所有实例的Countries,以求和并显示在类World_population的{​​{1}}字段上

我尝试过的

World

2 个答案:

答案 0 :(得分:4)

试一下:

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

有关聚合here的更多信息

答案 1 :(得分:1)

您可以在此处使用Sum()

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

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