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

Django中如何通过数据库函数提取CharField首词并聚合统计?

解决方案

可以利用PostgreSQL原生的split_part函数,结合Django为PostgreSQL提供的SplitPart数据库函数来实现需求。模型的@property是Python层面的方法,无法在数据库查询阶段执行,必须用数据库原生函数在数据库内完成字符串分割操作。

实现步骤:

  1. 导入PostgreSQL专属的SplitPart函数
  2. 通过annotate提取每条message的首词(以空格为分隔符取第1部分)
  3. 基于提取出的首词进行分组聚合统计

完整代码示例:

from django.contrib.postgres.functions import SplitPart
from django.db.models import Count, F

# 提取首词并聚合统计
queryset = Chat.objects.annotate(
    command=SplitPart(F('message'), ' ', 1)
).values('command').annotate(
    counts=Count('command')
).order_by('-counts')

说明:

  • SplitPart(F('message'), ' ', 1)对应PostgreSQL的split_part(message, ' ', 1),作用是将message字段按空格分割,取第1个部分(即首词)
  • 如果message中没有空格,该函数会返回整个message字符串,符合首词的定义
  • 如果需要过滤空字符串或无内容的message,可以在查询前添加filter(message__isnull=False, message__ne='')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:45:34