Ad

While Using Django-filter For Filtering How To Export The Filtered Values Into Csv File

- 1 answer

I have used django-filter module for filtering. Want to export the results into CSV file.

def bfs_version_filter(request):
    version_obj = bfs_versions.objects.all()
    filter_obj = version_filter(request.GET, queryset = version_obj)
    response = HttpResponse(content_type = 'text/csv')
    file_name = "version_filter"+str(date.today())+".csv"
    response['Content-Disposition'] = 'attachment; filename = "'+ file_name +'"' #edited by vennilam
    writer = csv.writer(response)
    for i in filter_obj:
        writer.writerow(i)
    return response

Getting below error: TypeError at /bfslite/version_filter/ 'version_filter' object is not iterable

Ad

Answer

Calling the constructor of a FilterSet subclass will not filter the queryset, it will construct an object of that subclass.

You can access the .qs attribute [readthedocs.io] to get access to the filtered queryset:

def bfs_version_filter(request):
    version_obj = bfs_versions.objects.all()
    filter_obj = version_filter(request.GET, queryset = version_obj).qs
    response = HttpResponse(content_type = 'text/csv')
    file_name = "version_filter"+str(date.today())+".csv"
    response['Content-Disposition'] = 'attachment; filename = "'+ file_name +'"' #edited by vennilam
    writer = csv.writer(response)
    for i in filter_obj:
        writer.writerow(i)
    return response
Ad
source: stackoverflow.com
Ad