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

如何在Django中从Date字段提取月份和年份列表

Django从Date字段提取所有年月组成列表的实现方法

方法1:ORM层面直接提取(推荐,数据库执行效率高)

适合所有数据量场景,无需拉取全表数据

  • 导入依赖
from django.db.models.functions import ExtractYear, ExtractMonth
  • 执行查询获取去重后的年月字典列表
# 请将下方Entry替换为你的模型名,publish_date替换为你的日期字段名
year_month_list = Entry.objects.annotate(
    year = ExtractYear('publish_date'),
    month = ExtractMonth('publish_date')
).values('year', 'month').distinct().order_by('-year', '-month')

返回结果示例:

<QuerySet [{'year': 2024, 'month': 5}, {'year': 2024, 'month': 3}, {'year': 2023, 'month': 12}]>

方法2:直接返回拼接好的年月字符串列表

如果需要直接得到2024年5月这类格式的字符串,可以用Concat拼接:

from django.db.models import CharField, Value
from django.db.models.functions import ExtractYear, ExtractMonth, Concat

# 请替换为你自己的模型和字段名
year_month_strs = Entry.objects.annotate(
    year = ExtractYear('publish_date'),
    month = ExtractMonth('publish_date')
).annotate(
    year_month = Concat(
        'year', Value('年'), 'month', Value('月'),
        output_field=CharField()
    )
).values_list('year_month', flat=True).distinct().order_by('-year', '-month')

返回结果示例:

<QuerySet ['2024年5月', '2024年3月', '2023年12月']>

方法3:小数据量场景的Python层处理

仅适合表数据量小于1万条的场景,逻辑更直观:

# 拉取所有日期字段值
all_dates = Entry.objects.values_list('publish_date', flat=True)
# 去重后排序
year_month_list = sorted({(date.year, date.month) for date in all_dates}, reverse=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:45:03