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

Django查询如何获取['start','end']格式扁平列表而非嵌套元组?

解决方法

你使用values()方法查询时,返回的QuerySet每个元素为包含字段名和对应值的字典,如果你拿到的是元组结构的结果,说明实际使用的是values_list()方法,该方法多字段查询时默认返回元组组成的QuerySet,因此你会得到[('START', 'END')]的结果,同时字段值为大写,需要额外做大小写转换和结构展开。

方案1:Python侧处理(适合数据量小的场景)

直接取值后展开元组、转小写即可:

# 取第一条数据的两个字段值,返回元组('START', 'END')
t_start_end = APIHistory.objects.values_list('status_start', 'status_end').first()
# 展开元组转小写,生成目标列表
codereview = [item.lower() for item in t_start_end]

如果是多条数据,要把所有行的两个字段值都合并到一个一维列表中,写法如下:

t_start_end = APIHistory.objects.values_list('status_start', 'status_end')
codereview = [item.lower() for row in t_start_end for item in row]

方案2:数据库层面转小写(适合数据量大的场景)

借助Django内置的Lower函数直接在查询时转小写,减少Python侧计算:

from django.db.models.functions import Lower

t_start_end = APIHistory.objects.annotate(
    start_lower=Lower('status_start'),
    end_lower=Lower('status_end')
).values_list('start_lower', 'end_lower').first()
codereview = list(t_start_end)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:54:06