Django如何按近24小时关联TagConnect数量排序取前5个Tag对象
实现方案
首先导入依赖:
from django.utils import timezone from django.db.models import Count, Q
核心查询代码(Django 2.0及以上版本适用):
# 计算24小时前的时间节点 time_24h_ago = timezone.now() - timezone.timedelta(hours=24) # 按最近24小时关联数倒序取前5个Tag top_tags = Tag.objects.annotate( # 统计每个Tag关联的、创建时间在24小时内的TagConnect数量 recent_connect_count=Count( 'tagconnect_set', filter=Q(tagconnect_set__created__gte=time_24h_ago) ) # 按统计数倒序排序,数量相同的Tag默认按主键排序,可按需调整 ).order_by('-recent_connect_count')[:5]
要点说明
- 代码中
tagconnect_set是Django外键默认生成的反向关联名,如果你在TagConnect的tag外键字段中自定义了related_name参数,需要替换为你自定义的名称。 - 如果需要过滤掉近24小时没有任何关联的Tag,可以在
annotate之后追加filter(recent_connect_count__gt=0)。 - 如果使用的Django版本低于2.0,不支持Count的filter参数,可以用条件表达式实现相同逻辑:
from django.db.models import Count, Case, When, IntegerField time_24h_ago = timezone.now() - timezone.timedelta(hours=24) top_tags = Tag.objects.annotate( recent_connect_count=Count( Case( When(tagconnect_set__created__gte=time_24h_ago, then=1), output_field=IntegerField() ) ) ).order_by('-recent_connect_count')[:5]
内容的提问来源于stack exchange,提问作者David Foie Gras
相关产品推荐
相关产品推荐

