You need to enable JavaScript to run this app. Django中如何按间隔两个外键的Person数量对City模型排序
优惠活动
大模型
产品
解决方案
定价
更多

Django中如何按间隔两个外键的Person数量对City模型排序

实现方案

你可以通过Django ORM的聚合查询能力直接完成该需求,步骤如下:

  1. 先从django.db.models导入聚合函数Count
  2. 对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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 22:03:01