使用django-filter过滤后导出CSV报错:'version_filter'对象不可迭代
Fixing "TypeError: 'version_filter' object is not iterable" in Django Filter to CSV Export
Hey there, let's sort out this issue quickly! The error you're seeing happens because you're trying to iterate directly over filter_obj—which is an instance of your version_filter (a FilterSet class from django-filter)—and FilterSet objects aren't iterable on their own. You need to access the filtered QuerySet instead, which lives at the qs attribute of the FilterSet.
Here's the corrected version of your view, plus some improvements to make the CSV output usable (like adding headers and properly formatting field values):
import csv from datetime import date from django.http import HttpResponse from .models import bfs_versions from .filters import version_filter # Make sure this imports your FilterSet class def bfs_version_filter(request): version_obj = bfs_versions.objects.all() filter_obj = version_filter(request.GET, queryset=version_obj) # Set up CSV response response = HttpResponse(content_type='text/csv') # Use f-strings for cleaner filename formatting file_name = f"version_filter_{date.today()}.csv" response['Content-Disposition'] = f'attachment; filename="{file_name}"' writer = csv.writer(response) # Write CSV headers (customize these to match your bfs_versions model fields) writer.writerow(['ID', 'Version Number', 'Release Date', 'Status']) # Iterate over the filtered QuerySet using filter_obj.qs for version in filter_obj.qs: # Write actual field values (adjust these to your model's fields) writer.writerow([ version.id, version.version_number, # Format date to avoid raw datetime object output version.release_date.strftime('%Y-%m-%d') if version.release_date else '', version.status ]) return response
Key Fixes & Notes:
filter_obj.qsinstead offilter_obj: This is the core fix—qsgives you the actual filtered database results (a QuerySet) that you can iterate over.- CSV Headers: Adding headers makes the exported file much easier to read for anyone using it.
- Field Value Handling: Directly writing model instances (like your original
writer.writerow(i)) would output Python object representations, not the actual data. We explicitly pull out field values here, and handle date formatting to avoid errors. - Cleaner String Formatting: Using f-strings for the filename and
Content-Dispositionmakes the code more readable and less error-prone than concatenation.
Just remember to adjust the header names and field references to match the actual fields in your bfs_versions model!
内容的提问来源于stack exchange,提问作者Epsi Vennila
相关产品推荐
相关产品推荐

