[英]How to create a form with fields for all instances of another model in Django?
[英]How to Sum all instances of a model in Django
这些是我的模特
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)
我正在尝试添加“ Countries
中所有实例的“ Population
, World_population
和并在“ World
”类的“ World
World_population
字段中显示
我尝试过的
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'))
有关聚合的更多信息,请点击此处
您可以在此处使用Sum(),
self.World_population = Countries.objects.aggregate(Sum('Population'))
https://docs.djangoproject.com/en/2.1/topics/db/aggregation/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.