[Answered ]-Django โ€“ StreamingHttpResponse export csv with fields name

1๐Ÿ‘

โœ…

You can add the header as the first element of the iterator that will be passed to csv_stream.export. One way of doing this is using itertools.chain

from itertools import chain

class descargarAsignacion(View):
    template_name='gestionAsignacion/detalle_Asignacion.html'

    def get(self, request,pk):

        # create the list in a separate variable. 
        #It's a list of tuple to be the same type of the returned queryset data
        values_list = [(
            "id",
            "idasignacion",
            "producto",
            "contrato",
        )]
           
        queryset=AsignacionSurtigas.objects.filter(idasignacion=pk)
   
        queryset_valueslist=queryset.values_list(
            *values_list    
            named=True,
        )
    
        csv_stream = CSVStream()

        # add values_list as the 1st item in the iterable
        return csv_stream.export("myfile", chain(values_list, queryset_valueslist))

Leave a comment