如何在此代码中写入非字段名称但是详细的字段名称?

时间:2013-03-07 17:09:48

标签: python django

如何在此代码中编写非字段名称但是字段的详细名称(在列标题中)(导出到xls)?

def export_as_xls(modeladmin, request, queryset):
    if not request.user.is_staff:
        raise PermissionDenied
    opts = modeladmin.model._meta

    wb = Workbook()
    ws0 = wb.add_sheet('0')
    col = 0
    field_names = []
    # write header row
    for field in opts.fields:
        ws0.write(0, col, field.name)
        field_names.append(field.name)
        col = col + 1

    row = 1
    # Write data rows
    for obj in queryset:
        col = 0
        for field in field_names:
            val = unicode(getattr(obj, field)).strip()
            ws0.write(row, col, val)
            col = col + 1
        row = row + 1   

    f = StringIO()
    wb.save(f)
    f.seek(0)
    response = HttpResponse(f.read(), mimetype='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename=%s.xls' % unicode(opts).replace('.', '_')
    return response

export_as_xls.short_description = "Export selected objects to XLS"

我看到field.name,但我不知道如何更改它。此代码来自django代码段

1 个答案:

答案 0 :(得分:0)

我可能会误解这个问题,但是如果你想改变field.name:

for field in opts.fields:
    field.name = 'Foo'

这会将所有字段名称更改为“Foo”