首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >django -带有字段名的StreamingHttpResponse导出csv

django -带有字段名的StreamingHttpResponse导出csv
EN

Stack Overflow用户
提问于 2022-06-16 16:50:40
回答 1查看 449关注 0票数 1

我已经创建了一个从数据库导出到csv文件的视图,代码运行良好,但是导出的csv文件没有字段名,如何添加它们呢?

我使用values_list是因为性能更高

我正在使用以下代码:

CSVStream.py:

代码语言:javascript
复制
class CSVBuffer:
    """An object that implements just the write method of the file-like
    interface.
    """
    def write(self, value):
        """Return the string to write."""
        return value

class CSVStream:
    """Class to stream (download) an iterator to a 
    CSV file."""
    def export(self, filename, iterator):
        # 1. Create our writer object with the pseudo buffer
        writer = csv.writer(CSVBuffer())

        # 2. Create the StreamingHttpResponse using our iterator as streaming content
        response = StreamingHttpResponse((writer.writerow(data) for data in iterator),
                                         content_type="text/csv")

        # 3. Add additional headers to the response
        response['Content-Disposition'] = f"attachment; filename={filename}.csv"
        # 4. Return the response
        return response

views.py

代码语言:javascript
复制
class descargarAsignacion(View):
    template_name='gestionAsignacion/detalle_Asignacion.html'
    
    def get(self, request,pk):
         # 1. Get the iterator of the QuerySet
               
        queryset=AsignacionSurtigas.objects.filter(idasignacion=pk)
       
        queryset_valueslist=queryset.values_list(
                "id",
                "idasignacion",
                "producto",
                "contrato",
                "nombre_suscriptor",
                "tipo_servicio",
                "total_deuda",
                "corriente_no_vencida_actual",
                "corrente_vencida",
                "total_deuda_corriente",
                "cuota_minima_agente",
                "politica_surtigas",
                "categoria",
                "estrato",
                "ref_anio",
                "historico_ref",
                "ciclo",
                "medidor",
                "lectura",
                "plan_acuerdo",
                "descripcion_barrio",
                "direccion",
                "dias_deuda",
                 named=True,
        )
        
        # 2. Create the instance of our CSVStream class
        csv_stream = CSVStream()

        # 3. Stream (download) the file
        return csv_stream.export("myfile", queryset_valueslist)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-17 04:27:29

您可以将头添加为将传递给csv_stream.export的迭代器的第一个元素。其中一种方法是使用itertools.chain

代码语言:javascript
复制
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))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72649321

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档