0

The below function exporting into csv properly but one thing missing is the header of those value.

How to write header of those values ?

I have quite a large queryset so i am using StreamingHttpResponse as suggested by django documentation but couldn't find the solution for adding a header of these values.

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
  
Mark
  • 89
  • 2
  • 8
  • may be of some help? https://stackoverflow.com/questions/20347766/pythonically-add-header-to-a-csv-file – Carlo Oct 18 '22 at 11:21

1 Answers1

1

To be able to add the header part you are trying, you should write them to the pseudo_buffer and yield them.

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)

and then use it like this:

response = StreamingHttpResponse(
    (iter_content(rows, headers)),
    status=200,
    content_type="text/csv",
)
    
Deniz Kaplan
  • 1,549
  • 1
  • 13
  • 18
  • thanks but now got one issue the values are coming in the same line as headers – Mark Oct 18 '22 at 11:32
  • I didn't test it but I think you're right. [Here](https://code.djangoproject.com/ticket/26040) is a possible fix for your issue. You need to add `seek` before yielding data and add a `truncate` statement after it. It seems like the documentation is wrong for your case. – Deniz Kaplan Oct 18 '22 at 11:43