You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含DISTINCT分组统计的SQL转换为Django ORM语句?

将SQL语句转换为Django ORM语句的解决方案

问题描述

需要转换的SQL语句:

select date(start_date) as start, count(*) as tournament_count, count(distinct(user_id)) from tournament group by start

尝试的ORM写法(无法实现DISTINCT统计部分):

Tournament.objects.annotate(date=TruncDate('start_date')).values('date').annotate(tournaments=Count('id')).order_by()

解决方案

要实现原SQL中count(distinct(user_id))的统计逻辑,只需在Count方法中传入distinct=True参数即可。完整的ORM写法如下:

from django.db.models import Count
from django.db.models.functions import TruncDate

Tournament.objects.annotate(date=TruncDate('start_date'))\
                  .values('date')\
                  .annotate(
                      tournament_count=Count('id'),
                      distinct_user_count=Count('user_id', distinct=True)
                  )\
                  .order_by()

关键说明

  • TruncDate('start_date')实现对start_date字段的日期截取,对应SQL中的date(start_date)
  • Count('id')对应原SQL的count(*),用于统计每日的赛事总数量
  • Count('user_id', distinct=True)精准对应count(distinct(user_id)),统计每日参与赛事的不同用户数
  • order_by()用于取消Django默认添加的排序规则,避免不必要的性能开销

内容的提问来源于stack exchange,提问作者pineforest22

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:15:34