如何使用QuerySet输出CSV文件

时间:2019-02-07 12:20:09

标签: django django-models django-forms django-templates django-views

我是输出CSV文件,但它为空白。我正在使用模板。有什么好办法为查询集输出csv

from django.http import HttpResponse
from django.template import Context, loader

def GenerateCSV(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'


    t = loader.get_template('company/company_csv.txt')
    data = {
            'companies':Company.objects.exclude(id=1).exclude(
                        company_is_deleted=True
                        ).annotate(
                        number_of_company_users=Count('userprofile')
                        )           
        }
    response.write(t.render(data))
    return response

file.txt

Sr. No, Company Name, Company Email, Count Of Total Users, Created Date, Current Monthly Payment, Is TABopts Customer, Status
{% for row in data %}"
{{ row.0|addslashes }}", "{{ row.1|addslashes }}", "{{ row.2|addslashes }}", "{{ row.3|addslashes }}", "{{ row.4|addslashes }}"
{% endfor %}

1 个答案:

答案 0 :(得分:1)

我发现了一种新的方法。

# Outputting  CSV
import csv
from django.http import HttpResponse

def GenerateCSV(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="Company_Report.csv"'

    query_set = Company.objects.exclude(id=1).exclude(
                            company_is_deleted=True
                            ).annotate(
                            number_of_company_users=Count('userprofile')
                        ) 

    output = []

    for query in query_set:
        output.append([
            query.company_name, 
            query.company_email, 
            query.number_of_company_users, 
            query.company_created, 
            query.company_monthly_payment, 
            query.company_tab_opts, 
            query.company_status, 
            ])

    writer = csv.writer(response)
    writer.writerow(['Company Name', 'Company Email', 'Count Of Total Users', 'Created Date', 'Current Monthly Payment', 'Is TABopts Customer', 'Status'])
    #CSV Data
    writer.writerows(output)

    return response