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

如何从Django QuerySet中提取指定字段的纯值列表?

解决Django QuerySet提取单个字段值列表的问题

你可以用两种简单方法实现需求:

方法1:直接用values_list(推荐)

Django ORM提供了values_list方法,专门用来提取指定字段的值,配合flat=True参数可以直接得到单个值的QuerySet,转成列表就是你要的格式:

# 直接查询并提取month值列表
month_list = list(
    Planning_quantity_data.objects
    .filter(product=product, upload_month=upload_month)
    .values_list('month', flat=True)
    .distinct()
)

values_list('month', flat=True)会返回包含每个month值的QuerySet,再用list()转成普通列表即可,这种方式比先查字典再处理更高效。

方法2:对已有的字典QuerySet做列表推导

如果已经拿到了那个包含{'month': 'xxx'}的QuerySet(比如你代码里的un_month),用列表推导式逐个提取字典里的month值:

un_month = Planning_quantity_data.objects.values('month').filter(product=product, upload_month=upload_month).distinct()
month_list = [item['month'] for item in un_month]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:01:08