下载Django中的对象子集

时间:2011-11-14 15:57:09

标签: python django

我的网站上有一个包含多个表单的搜索页面,还有一个显示搜索结果的页面。我希望用户能够下载搜索结果(作为文本文件或其他)。

这基本上就是我的观点:

def search_page(request):
    form = SearchOptions()
    if request.method == 'POST':
        #filter the objects based on the input in the forms
        return render_to_response('results.html', {'filtered_objects' : filtered_objects}, context_instance=RequestContext(request))

    else:
        return render_to_response('search_page.html', {'form' : form}, context_instance=RequestContext(request))

理想情况下,我想要另一种处理下载的视图,例如

def download(filtered_objects):
    #process file
    return downloadable_file

我有一个可以运行的下载视图(它允许我下载一个虚拟文件),但我不知道如何将filtered_objects传递给它。

2 个答案:

答案 0 :(得分:2)

您可以定义一个实用程序搜索功能,根据搜索参数返回搜索结果;并将其留给视图调用此函数并处理结果应如何呈现(html或csv download或json或其他)。

或者,您可以在视图中添加一个参数(在url中或作为get参数),以定义输出格式并返回相应的响应。但要注意无效参数。

答案 1 :(得分:0)

将查询结果导出为CSV文件是否足够?

试试这个并查看它是否适合您想要做的事情: https://docs.djangoproject.com/en/dev/howto/outputting-csv/?from=olddocs