如何在导出django查询集到csv时写入行名称?

kdfy810k  于 2022-12-06  发布在  Go
关注(0)|答案(1)|浏览(126)

下面的函数导出到csv正确,但缺少一件事是这些值的标题。
如何编写这些值的头文件?
我有一个相当大的查询集,所以我使用了django文档中建议的StreamingHttpResponse,但是找不到添加这些值的头部的解决方案。

class Echo:
    def write(self, value):
        return value

def some_streaming_csv_view(request):
    rows = MyModel.objects.values_list("value1", "value2")
    pseudo_buffer = Echo()
    writer = csv.writer(pseudo_buffer)

    writer.writerow(["name1", "name2"]) # didn't work

    response = StreamingHttpResponse(
            (writer.writerow(row) for row in rows),
            status=200,
            content_type="text/csv",
        )
    response["Content-Disposition"] ='attachment; filename=filname.csv'
    return response
afdcj2ne

afdcj2ne1#

为了能够添加您正在尝试的头部分,您应该将它们写入pseudo_buffer并生成它们。

def iter_content(rows, headers):
    pseudo_buffer = Echo()
    writer = csv.writer(pseudo_buffer)
    yield pseudo_buffer.write(headers)
    for row in rows:
        yield writer.writerow(row)

然后像这样使用它:

response = StreamingHttpResponse(
    (iter_content(rows, headers)),
    status=200,
    content_type="text/csv",
)

相关问题