使用原始sql导出到django中的CSV / Excel文件

时间:2015-10-23 07:42:50

标签: python django excel csv django-views

在django中生成excel / csv文件时遇到问题主要是因为我使用raw sql(直接)查询数据库。我只能访问数据库而不是模型类。这是我的代码段。

我收到错误'dict'对象没有属性'todo_job'

查看代码

def query_to_dicts(query_string, *query_args):
"""Run a simple query and produce a generator
that returns the results as a bunch of dictionaries
with keys for the column values selected.
"""
    #log.debug(str(dir(connection)))
    cursor = connection.cursor()
    #log.debug(str(dir(cursor)))
    cursor.execute(query_string, query_args)
    #log.debug(cursor.rowcount)log
    col_names = [desc[0] for desc in cursor.description]
    #log.debug(str(col_names))
    while True:
        row = cursor.fetchone()
        if row is None:
            break

        row_dict = dict(izip(col_names, row))
        yield row_dict

    return

def excel(request):
    todo_obj = query_to_dicts('''SELECT * FROM users''')

    response = HttpResponse(mimetype='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename=elagu.xls'
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet("Todo")

    row_num = 0

    columns = [
        (u"ID", 6000),
        (u"t_stamp", 8000),

    ]

    font_style = xlwt.XFStyle()
    font_style.font.bold = True

    for col_num in xrange(len(columns)):
        ws.write(row_num, col_num, columns[col_num][0], font_style)
        # set column width
        ws.col(col_num).width = columns[col_num][1]

    font_style = xlwt.XFStyle()
    font_style.alignment.wrap = 1

    for obj in todo_obj:
        row_num += 1
        row = [
            row_num,
            obj.todo_job,
            obj.created_date.strftime("%A %d. %B %Y"),
        ]
        for col_num in xrange(len(row)):
            ws.write(row_num, col_num, row[col_num], font_style)

    wb.save(response)
    return response

1 个答案:

答案 0 :(得分:0)

您正在尝试访问那些地方不存在的dict对象的属性:

obj.todo_job
obj.creation_date

要在Python中访问dict的值,您需要使用带有相关键的下标运算符([])作为字符串,这将给出:

obj['todo_job']
obj['creation_date']

有关详细信息,请参阅Python dict documentation