Django中如何按间隔两个外键的Person数量对City模型排序
实现方案
你可以通过Django ORM的聚合查询能力直接完成该需求,步骤如下:
- 先从django.db.models导入聚合函数
Count - 对City查询集做关联统计后排序
代码示例
from django.db.models import Count # 按人口降序排序(人口多的在前) sorted_cities = City.objects.annotate( total_population=Count('area__person') ).order_by('-total_population')
代码说明
- 这里使用双下划线
__跨多层外键关联,area__person表示统计每个City关联的所有Area下的所有Person数量 annotate会给每个返回的City对象新增total_population属性,存储统计得到的人口数order_by参数里的-代表降序排序,去掉-则为人口从少到多升序排序- 如果需要过滤掉人口为0的城市,可追加
filter(total_population__gt=0)条件:sorted_cities = City.objects.annotate( total_population=Count('area__person') ).filter(total_population__gt=0).order_by('-total_population')
内容的提问来源于stack exchange,提问作者shubham
相关产品推荐
相关产品推荐

