如何使用annotations将RAW SQL关联统计转换为Django QuerySet
Django QuerySet 实现方案
完全匹配原RAW SQL逻辑的写法
该写法生成的SQL结构和你手写的RAW几乎完全一致,避免多表JOIN的笛卡尔积问题:
首先导入依赖模块:
from django.db.models import OuterRef, Subquery, Count, Q from django.db.models.functions import Coalesce
然后构造两个统计用的相关子查询:
# 统计当前Winemaker下状态为20的Wine数量 wines_count_sub = Wine.objects.filter( winemaker=OuterRef("pk"), status=20 ).values("winemaker").annotate( cnt=Count("id") ).values("cnt") # 统计当前Winemaker下关联的符合条件的Post数量(Wine状态20、Post状态20) wineposts_count_sub = Post.objects.filter( wine__winemaker=OuterRef("pk"), wine__status=20, status=20 ).values("wine__winemaker").annotate( cnt=Count("id") ).values("cnt")
最后构造主查询,将两个统计值注解到Winemaker对象上:
winemaker_list = Winemaker.objects.annotate( # Coalesce用于将无匹配结果的NULL值转为0,和SQL count()的默认返回值对齐 wines_count=Coalesce(Subquery(wines_count_sub), 0), wineposts_count=Coalesce(Subquery(wineposts_count_sub), 0) )
更简洁的Django原生聚合写法
适用于Django 2.0及以上版本,性能更优:
from django.db.models import Count, Q winemaker_list = Winemaker.objects.annotate( wines_count=Count( "wine__id", filter=Q(wine__status=20), distinct=True # 避免多表JOIN导致的Wine计数重复 ), wineposts_count=Count( "wine__post__id", filter=Q(wine__status=20, wine__post__status=20) ) )
注意事项
- 如果你的模型外键配置了
related_name参数,需要将代码中的反向关联名(如wine、post)替换为你实际定义的名称 - 上述两种写法返回的结果和你提供的RAW SQL完全一致,可直接替换使用
内容的提问来源于stack exchange,提问作者akushyn
相关产品推荐
相关产品推荐

