gpt4 book ai didi

python - 如何在 Django 中对模型的所有实例求和

转载 作者:行者123 更新时间:2023-11-28 21:35:15 26 4
gpt4 key购买 nike

这些是我的模型

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类里面的田野World

我尝试过的

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()

最佳答案

试一下:

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

有关聚合的更多信息 here

关于python - 如何在 Django 中对模型的所有实例求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52462931/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com