如何将含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
相关产品推荐
相关产品推荐

