在django上导出csv文件

时间:2017-02-27 11:45:11

标签: django view export-to-csv

Link: <a href="{% url 'testing:export_csv' tr_details.tr_id %}">Export CSV</a>

当我点击锚链接时,我想导出csv文件,然后转到确认页面。

{% extends "users/UserBar.html" %}
{% load staticfiles %}<!--Loading for CSS sheet-->
{% block css %}
<link rel="stylesheet" type="text/css" href="{% static 'testing/style.css' %}" />
{% endblock css %}

{% block title %}{{ tr_info.tr_id }} Export to CSV {% endblock title %}
{% block header %}<a href="{% url 'testing:TrDetail' tr_info.tr_id %}">{{ tr_info.tr_id }}</a> Export to CSV {% endblock header %}

{% if error_message %}
    <p><strong>{{ error_message }}</strong></p>
{% endif %}

{% csrf_token %}

{% block main %}
    <p>The file has been export to CSV for tr id : {{ tr_info.tr_id }} </p>
{% endblock main %}

一切正常,直到这一步。

import csv

from django.db import connections

from django.http import HttpResponse

from django.views.generic import ListView

from testing.models import TrRunSummary, TrDetails


class ExportCsv(ListView):
    """Displays the different tests performed on the specified test request"""
    template_name = 'testing/tr_export_csv.html'
    context_object_name = 'export_csv'

    def get_context_data(self, **kwargs):
        context = super(ExportCsv,self).get_context_data(**kwargs)
        context['tr_info'] = self.tr_info()


        return context

    def get_queryset(self):
        qtr_id = self.kwargs['trID']
        s = str(qtr_id)
        # print s
        # print type(s)

        cursor = connections['default'].cursor()

        query =("SELECT results_stb_id, results_stbs.stb_id, stb_inv.mac_add, "
        "test_functionality.test_functionality_code, test_cases.test_case_no, "
        "SCRIPT.option_name AS script_result, POST.option_name AS post_result, "
        "results_tests.started, results_tests.stopped, results_tests.test_duration, builds.baseline, "
        "builds.build_type, stb_hw_info.stb_type, defects.defect_name, parser_output, log_url, "
        "script_health_score, post_health_score FROM results_stbs "
        "JOIN tr_test_cases "
        "ON tr_test_cases.tr_test_case_id=results_stbs.tr_test_case_id "
        "JOIN test_cases "
        "ON test_cases.test_case_id=tr_test_cases.test_case_id "
        "JOIN test_functionality "
        "ON test_functionality.test_functionality_id=test_cases.test_functionality_id "
        "LEFT JOIN stb_inv "
        "ON results_stbs.stb_id=stb_inv.stb_id "
        "LEFT JOIN result_options AS SCRIPT "
        "ON results_stbs.script_result=SCRIPT.result_option_id "
        "LEFT JOIN result_options AS POST "
        "ON results_stbs.post_result=POST.result_option_id "  
        "JOIN results_tests "
        "ON results_stbs.results_test_id=results_tests.results_test_id "
        "JOIN builds "
        "ON builds.build_id=results_stbs.build_id "
        "JOIN stb_hw_info_ids "
        "ON stb_hw_info_ids.stb_hw_info_ids_id=results_stbs.stb_hw_info_ids_id "
        "JOIN stb_hw_info "
        "ON stb_hw_info.stb_hw_info_id=stb_hw_info_ids.stb_hw_info_id "
        "LEFT JOIN defects_tests "
        "ON results_tests.results_test_id=defects_tests.results_test_id "
        "LEFT JOIN defects "
        "ON defects.defect_id=defects_tests.defect_id "
        "WHERE tr_test_cases.tr_id = '%s' AND script_result IN (1, 3, 8) " 
        "OR tr_test_cases.tr_id = '%s' AND post_result IN (1, 3, 8) "
        "ORDER BY results_stb_id ASC ") % (s, s)

        cursor.execute(query)
        rows = cursor.fetchall()
        return rows


    def tr_info(self):
        tr_id = self.kwargs['trID']
        tr_info = TrDetails.objects.get(
            tr_id=tr_id,
        )
        return tr_info

对不起,这个问题可能太简单了。但是,我是Django框架的新手。当用户单击上面的链接时,我想传递get_queryset()函数的返回值来导出csv文件。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

我认为您可以在def get(self, request, *args, **kwargs)或其他功能中处理它,然后创建一个特定视图来呈现content_type = 'text/csv',因为在您的ExportCsv(ListView)用于html模板。

更多信息,您可以按照以下答案进行操作;

我将举例说明如何做到这一点。

import csv
from django.http import HttpResponse
# and others imported modules...


def export_csv_file(request, queryset):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment;filename=export.csv'

    # opts = queryset.model._meta
    # field_names = [field.name for field in opts.fields]

    writer = csv.writer(response)
    # write a first row with header information
    # writer.writerow(field_names)

    # write data rows
    # I suggest you to check what output of `queryset`
    # because your `queryset` using `cursor.fetchall()`
    # print(queryset)
    for row in queryset:
        writer.writerow(row)
    return response


class ExportCsvListView(ListView):
    template_name = 'testing/tr_export_csv.html'
    context_object_name = 'export_csv'

    def get_queryset(self):
        qtr_id = self.kwargs['trID']
        s = str(qtr_id)
        cursor = connections['default'].cursor()

        query =(".....") % (s, s)

        cursor.execute(query)
        rows = cursor.fetchall()
        return rows

    def get(self, request, *args, **kwargs):
        self.format = request.GET.get('format', False)

        # my/url/?format=csv
        if self.format == 'csv':
            return export_csv_file(request, self.get_queryset())

        return super(ExportCsvListView, self).get(request, *args, **kwargs)


    def get_context_data(self, **kwargs):
        context = super(ExportCsvListView, self).get_context_data(**kwargs)
        context['tr_info'] = self.tr_info()
        return context