使用 Django 生成 CSV 文件(动态内容)

发布于 2024-09-29 19:13:02 字数 921 浏览 1 评论 0原文

在我的 view.py 中,我有两个函数,一个函数处理来自表单的输入并输出过滤后的列表,另一个函数应该将此列表导出到 CSV。

这是我的第一个函数的返回:

return render_to_response('templateX.html',
{
 'queryset': queryset,
 'filter_form': filter_form,
 'validated': validated,
},
 context_instance = RequestContext(request)
 )

这是导出函数:

def export_to_csv(request):
    # get the response object, this can be used as a stream.
    response = HttpResponse(mimetype='text/csv')
    # force download.
    response['Content-Disposition'] = 'attachment;filename=export.csv'
    # the csv writer
    writer = csv.writer(response)
    qs = request.session['queryset']
    for cdr in qs:
        writer.writerow([cdr['calldate'], cdr['src'], cdr['dst'], ])
    return response   

我不确定如何从我的第一个函数中获取 queryset,其中包含我想要在 CSV 中包含的项目列表以及在我的 export_to_csv 函数中使用它。 或者最好的方法是将这两个功能结合起来,让用户单击复选框是否要下载 CSV 文件。 任何帮助将不胜感激。

Inside my view.py, I have two functions, one that processes input from a form and outputs a filtered list, and another that is supposed to export this list to CSV.

Here is the return of my first function:

return render_to_response('templateX.html',
{
 'queryset': queryset,
 'filter_form': filter_form,
 'validated': validated,
},
 context_instance = RequestContext(request)
 )

Here is the exporting function:

def export_to_csv(request):
    # get the response object, this can be used as a stream.
    response = HttpResponse(mimetype='text/csv')
    # force download.
    response['Content-Disposition'] = 'attachment;filename=export.csv'
    # the csv writer
    writer = csv.writer(response)
    qs = request.session['queryset']
    for cdr in qs:
        writer.writerow([cdr['calldate'], cdr['src'], cdr['dst'], ])
    return response   

I'm not sure how to get the queryset from my first function, which contains a list of the items I want in my CSV and use it in my export_to_csv function.
Or would the best way be combining these two functions and have the user click on a checkbox whether he/she wants to download a CSV file.
Any help would be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

身边 2024-10-06 19:13:02

我建议将这些组合到一个视图函数中,该函数需要一个额外的参数:

def my_view(request, exportCSV):
    # ... Figure out `queryset` here ...

    if exportCSV:
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment;filename=export.csv'
        writer = csv.writer(response)
        for cdr in queryset:
            writer.writerow([cdr['calldate'], cdr['src'], cdr['dst'], ])
        return response
    else:
        return render_to_response('templateX.html', {'queryset': queryset,
            'filter_form': filter_form, 'validated': validated},
            context_instance = RequestContext(request))

然后,在您的 urls.py 中,在您的 urlpatterns 中添加类似这样的内容:

url(r'^form', 'my_view', {"exportCSV": False}, name="form"),
url(r'^csv', 'my_view', {"exportCSV": True}, name="export"),

I'd recommend combining these into one view function which takes an extra parameter:

def my_view(request, exportCSV):
    # ... Figure out `queryset` here ...

    if exportCSV:
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment;filename=export.csv'
        writer = csv.writer(response)
        for cdr in queryset:
            writer.writerow([cdr['calldate'], cdr['src'], cdr['dst'], ])
        return response
    else:
        return render_to_response('templateX.html', {'queryset': queryset,
            'filter_form': filter_form, 'validated': validated},
            context_instance = RequestContext(request))

Then, in your urls.py, put something like this in your urlpatterns:

url(r'^form', 'my_view', {"exportCSV": False}, name="form"),
url(r'^csv', 'my_view', {"exportCSV": True}, name="export"),
傻比既视感 2024-10-06 19:13:02

恕我直言,最好的方法是将它们组合起来并从显式查询集生成 CSV 数据。然后可以将其重写为一般内容,例如(未测试):

def export_to_csv(request, queryset, fields):
    response = ...
    writer = csv.writer(response)
    for obj in queryset:
        writer.writerow([getattr(obj, f) for f in fields])
    return response

您可以像这样使用:

def my_view(request):
    calls = Call.objects.all()
    return export_to_csv(request, calls, fields = ('calldate', 'src', 'dst'))

--

您提供的示例代码假设 QuerySet 在会话数据中设置,这可能会导致大量错误和安全问题。如果将会话存储在数据库中,则最终可能会读取数据,只是以效率低得多的形式将其写回。

IMHO, the best would be to combine them and generate the CSV data from an explicit queryset. This could then be rewritten to something general like(not tested):

def export_to_csv(request, queryset, fields):
    response = ...
    writer = csv.writer(response)
    for obj in queryset:
        writer.writerow([getattr(obj, f) for f in fields])
    return response

Which you can use like this:

def my_view(request):
    calls = Call.objects.all()
    return export_to_csv(request, calls, fields = ('calldate', 'src', 'dst'))

--

The example code you provided assumes the QuerySet is set in the session data, which could cause you tons of bugs as well as security problems. If you store sessions in your database, you could end up reading data, just to write it back in a much less efficient form.

墟烟 2024-10-06 19:13:02

我找到了一种与 knutin 不同的方法。
我在函数或全局变量之外声明了一个名为 csv_list = [] 的空列表。

在我的主函数(根据用户输入进行处理和过滤的函数)中,我将此 csv_list 设为全局,以便将其设置为查询集的“更新”版本。
然后生成 csv,很简单:
对于 csv_list 中的调用:
writer.writerow([call.src, call.dst])
返回响应

现在工作正常。

I found a way to do it that's different than knutin's.
I declared an empty list called csv_list = [] outside my functions, or global variable.

In my main function (the one that processes and filters based on user input), I make this csv_list global so that it gets set to the "updated" version of the queryset.
Then to generate the csv, it's as easy as:
for call in csv_list:
writer.writerow([call.src, call.dst])
return response

It's working reasonably now.

百变从容 2024-10-06 19:13:02

以下代码接收 Django 查询集并输出 CSV 文件。

用法::

<块引用>

从 utils 导入 dump2csv

从 dummy_app.models 导入 *

qs = DummyModel.objects.all()

dump2csv.dump(qs, './data/dump.csv')

脚本:

import csv
from django.db.models.loading import get_model

def dump(qs, outfile_path):

    model = qs.model
writer = csv.writer(open(outfile_path, 'w'))

headers = []
for field in model._meta.fields:
    headers.append(field.name)
writer.writerow(headers)

for obj in qs:
    row = []
    for field in headers:
        val = getattr(obj, field)
        if callable(val):
            val = val()
        if type(val) == unicode:
            val = val.encode("utf-8")
        row.append(val)
    writer.writerow(row)

The following takes in a Django queryset and spits out a CSV file.

Usage::

from utils import dump2csv

from dummy_app.models import *

qs = DummyModel.objects.all()

dump2csv.dump(qs, './data/dump.csv')

The script:

import csv
from django.db.models.loading import get_model

def dump(qs, outfile_path):

    model = qs.model
writer = csv.writer(open(outfile_path, 'w'))

headers = []
for field in model._meta.fields:
    headers.append(field.name)
writer.writerow(headers)

for obj in qs:
    row = []
    for field in headers:
        val = getattr(obj, field)
        if callable(val):
            val = val()
        if type(val) == unicode:
            val = val.encode("utf-8")
        row.append(val)
    writer.writerow(row)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文