[英]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.