首先,很抱歉找不到适合我问题的标题。
我在views.py中使用了一个查询集。它对国家进行分组,并对城市人口进行汇总。没有问题,我可以将人口和分组国家的总和显示为{% for query in queryset %}<li>{{query.countryname__name}} : {{query.country_population}}</li>{% endfor %}
但我如何添加我在models.py上定义的国家的位置?或者其他相关的县领域?因为当我使用City.objects.values('countryname__name')
时,我会丢失数据,并且无法到达任何字段作为City.objects.all()
:(
型号.py
class Seasons(models.Model):
season = models.CharField(max_length=50)
def __str__(self):
return self.season
class Country(models.Model):
name = models.CharField(max_length=30)
location = models.CharField(max_length=50)
flag_def = models.CharField(max_length=50, null = True, blank = True)
season_country = models.ManyToManyField("Seasons")
def __str__(self):
return self.name
class City(models.Model):
name = models.CharField(max_length=30)
countryname = models.ForeignKey(Country, on_delete=models.CASCADE)
population = models.PositiveIntegerField()
def __str__(self):
return self.name
views.py
def index(request):
queryset = City.objects.values('countryname__name').annotate(country_population=Sum('population'))
content = {
"queryset" : queryset
}
return render(request,"index.html", content)
template.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Population</h1>
{% for query in queryset %}
<li>{{query.countryname__name}} : {{query.country_population}} {{query.countryname__name.location}} </li>
{% endfor %}
</body>
</html>
显示器:
Population
Brazil : 7700000 (in here i would like to display Brazil's Season or location)
England : 3000000 (in here i would like to display England's Season or location)
Turkey : 14000000 (in here i would like to display Turkey's Season or location)
数据库=https://ibb.co/bQNc6G6
感谢Advance。。。
你尝试过吗:
from django.db.models import F
queryset = City.objects.values('countryname__name').annotate(country_population=Sum('population'), country_location=F('countryname__location'))
这是关于F((的文档