python - 如何从我的 Django 数据库中检索行数据作为列表?

标签 python mysql django excel django-queryset

我想以列表的形式检索 Django 数据库表行中的数据,以便我可以对其进行迭代并将列表的每个值写入 Excel 电子表格。我尝试使用字典来执行此操作,但字典在 Python 中没有排序,所以我的专栏变得乱七八糟。我需要我的 Excel 电子表格看起来与我的数据库表一样,而不是随机排列。我怎样才能做到这一点?

当前代码:

def dump_attorneys_to_xlsx(request):
    if request.GET.get('export'):
        output = BytesIO()
        workbook = xlsxwriter.Workbook(output, {'in_memory': True})
        worksheet = workbook.add_worksheet('Summary')

        attorneys = Attorney.objects.all().values()
        # Write header
        worksheet.write_row(0, 0, attorneys[0].keys())
        # Write data
        for row_index, row_dict in enumerate(attorneys, start=1):
            worksheet.write_row(row_index, 0, row_dict.values())
        workbook.close()

        output.seek(0)

        response = HttpResponse(output.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = 'attachment; filename=summary.xlsx'

最佳答案

您可以使用 csv.DictWriter可以采用字典列表而不是列表的对象,或者使用 QuerySet 的 values_list方法而不是 values 来返回行列表而不是字典。


否则,您可以使用以下命令写入文件(性能不是很好):

keys = attorneys[0].keys()
worksheet.write_row(0, 0, keys)
# Write data
for row_index, row_dict in enumerate(attorneys, start=1):
    row = [row_dict[k] for k in keys]
    worksheet.write_row(row_index, 0, row)

关于python - 如何从我的 Django 数据库中检索行数据作为列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40221260/

相关文章:

python - 如何使用 Dual_annealing 设置简单的线性约束?

C# ODBC 异常不正确的字符串值

python - 我不能在 Django 项目中使用对象属性

django - 错误 : Using the URLconf defined in mysite. urls,Django 尝试了这些 URL 模式

python - PyQt 使用 ctrl+Enter 触发按钮

python - 使用 Pandas 在日期的两个时间之间进行插值

php - 使用 PHP 代码更改 MySQL 中的行

php - MySQL+PHP 可以使用 SELECT AS 重新定义表名吗?

python - Django 引荐来源问题

python - 如何用scrapy抓取交互式图表?