Django:如何在两个关联模型中统计各国城市数量
实现国家-城市数量统计表格的代码实现
1. views.py 代码实现
在视图中用Django的聚合查询高效完成每个国家的城市数量统计,避免模板层多次请求数据库:
from django.shortcuts import render from .models import Countries from django.db.models import Count def country_city_count(request): # 通过related_name关联统计每个国家的城市数量,distinct避免多对多关联重复计数 countries_data = Countries.objects.annotate( city_count=Count('Rightful', distinct=True) ) return render(request, 'country_city_count.html', {'countries_data': countries_data})
2. HTML模板(country_city_count.html)代码实现
编写表格展示统计结果,遍历视图传递的数据:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>国家-城市数量统计</title> <style> table { border-collapse: collapse; width: 60%; margin: 20px auto; } th, td { border: 1px solid #ddd; padding: 8px; text-align: center; } th { background-color: #f2f2f2; } </style> </head> <body> <h2 style="text-align: center;">国家拥有城市数量统计</h2> <table> <thead> <tr> <th>国家名称</th> <th>拥有城市数量</th> </tr> </thead> <tbody> {% for country in countries_data %} <tr> <td>{{ country.country }}</td> <td>{{ country.city_count }}</td> </tr> {% empty %} <tr> <td colspan="2">暂无数据</td> </tr> {% endfor %} </tbody> </table> </body> </html>
补充说明
- 用
annotate+Count在数据库层面完成统计,比模板中调用{{ country.Rightful.count }}更高效,减少数据库查询次数 - 需在
urls.py中配置对应路由,将country_city_count视图映射到具体访问路径
内容的提问来源于stack exchange,提问作者Mahdi Sedighi Moghaddam
相关产品推荐
相关产品推荐

