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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 22:54:00