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

Django使用xlwt导出Excel时报Orden对象无values_list属性如何解决

Django导出指定ID数据为Excel时values_list报错的解决方案

错误原因

两个问题共同导致报错:

  • Orden.objects.get(id=id)返回的是单个Orden模型实例对象,而values_list是Django查询集(QuerySet)专属方法,单个实例不存在该方法,所以抛出属性不存在的报错。
  • 原代码中调用values_list后未将返回结果赋值给变量,后续遍历的还是原对象,即使解决了第一个问题也无法正常写入数据。

解决方案

提供两种可选实现方式:

方式一:使用filter获取查询集调用values_list

将获取数据的逻辑替换为filter查询,得到QuerySet后直接调用values_list,适合可能返回多条数据的场景:

# 替换原获取rows的两行代码
rows = Orden.objects.filter(id=id).values_list('num_orden', 'client', 'fechain', 'instrumento', 'marca')

方式二:直接读取单个实例属性拼接数据

如果确定只会查询到单条数据,可以直接读取实例属性生成行数据,逻辑更直观:

# 替换原获取rows的两行代码
orden_obj = Orden.objects.get(id=id)
rows = [
    [orden_obj.num_orden, orden_obj.client, orden_obj.fechain, orden_obj.instrumento, orden_obj.marca]
]

修正后完整可运行代码

这里采用方式一的实现:

from django.shortcuts import render
from clientesapp.models import Cliente, Orden
from django.http import HttpResponse
import xlwt

def excel_create(request, id):
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="recibo.xls"'

    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('recibo')

    row_num = 0
    # 表头样式
    font_style = xlwt.XFStyle()
    font_style.font.bold = True
    columns = ['Orden', 'Cliente', 'Entrada', 'Instrumento', 'Marca']
    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style)

    # 内容样式
    font_style = xlwt.XFStyle()
    rows = Orden.objects.filter(id=id).values_list('num_orden', 'client', 'fechain', 'instrumento', 'marca')
    
    for row in rows:
        row_num += 1
        for col_num in range(len(row)):
            ws.write(row_num, col_num, row[col_num], font_style)

    wb.save(response)
    return response

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 10:18:03