首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python XLWT外键值

Python XLWT外键值
EN

Stack Overflow用户
提问于 2013-02-23 15:15:15
回答 1查看 585关注 0票数 2

我正在导出数据库字段到Excel文件,一切正常,但我的外键字段打印为外键ID,而不是实际值。

我怎么才能修复它?

下面是我的代码:

代码语言:javascript
复制
    book = xlwt.Workbook(encoding='utf8')
    sheet = book.add_sheet('Expense summary', cell_overwrite_ok=True)
    header_style = xlwt.easyxf('font:height 280, color blue, bold 1; border: bottom thick;')
    sum_style = xlwt.easyxf('font:height 200, color green, bold 1; border: top thick;')
    date_style = xlwt.XFStyle()
    date_style.num_format_str = 'DD-MM-YYYY'
    currency_style = xlwt.XFStyle()
    currency_style.num_format_str = '#,##0.00'
    xls_values = expense.filter(
                                user=request.user.id).values_list('date', 'amount', 'towho', 'forwhat', 'category', 'payment_method')
    headers = (ugettext("Date"), ugettext("Amount"), ugettext("To who"), ugettext("For what"), ugettext("Category"), ugettext("Payment method"))
    for i, header in enumerate(headers):
        col_width = 256 * 20
        sheet.col(i).width = col_width
        sheet.row(0).write(i, header, header_style)
    for row, rowdata in enumerate(xls_values):
        for col, val in enumerate(rowdata):
            if col == 0:
                sheet.write(row + 1, col, val, date_style)
            else:
                if col == 1:
                    sheet.write(row + 1, col, val, currency_style)
                else:
                    sheet.write(row + 1, col, val)
    response = HttpResponse(mimetype='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=sample.xls'
    book.save(response)
    return response

category字段返回ID号而不是值。

提前感谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-23 20:30:22

不是枚举rowdata,而是逐个字段生成行字段:

代码语言:javascript
复制
for row, o in enumerate(xls_values):
    sheet.write(row + 1, 0, o.my_first_field, date_style)
    sheet.write(row + 1, 1, o.my_second_field, val, currency_style)
    sheet.write(row + 1, 2, o.my_category_field.name, val) # assuming name is what you want
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15038153

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档