问题
I am trying to figure out how to do a simple export of data to a CSV file. I found an example that works....
def export_data(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="users.csv"'
writer = csv.writer(response)
writer.writerow(['username', 'First name', 'Last name', 'Email address'])
users = User.objects.all().values_list('name','userid')
for user in users:
writer.writerow(user)
return response
The code above works as you would expect, exporting all of the users from User.objects.all() to the spreadsheet. However, I am trying to do this from a DetailView and only get the data for the user that is being viewed, not the entire model, with the .all().
From what I gather, in order to do this in a DetailView, I believe I need to do something like...
class ExportDataDetailView(LoginRequiredMixin,DetailView):
model = Author
context_object_name = 'author_detail'
....And then perhaps I need to override get_queryset? It seems like overkill though because I'm already in the DetailView...
Thanks for any pointers in the right direction in advance.
回答1:
When you are using DetailView
, means you can use only object. If you want to export that, you can do the following:
class ExportDataDetailView(LoginRequiredMixin,DetailView):
model = Author
context_object_name = 'author_detail'
def render_to_response(self, context, **response_kwargs):
user = context.get('author_detail') # getting User object from context using context_object_name
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="users.csv"'
writer = csv.writer(response)
writer.writerow(['username', 'First name', 'Last name', 'Email address'])
writer.writerow([user.username, user.first_name, ...])
return response
Now, if you want all users' data, then you can use ListView:
from django.views.generic.list import ListView
class ExportDataListView(LoginRequiredMixin,ListView):
model = Author
context_object_name = 'authors'
def render_to_response(self, context, **response_kwargs):
authors = context.get('authors') # getting all author objects from context using context_object_name
users = authors.values_list('name','userid', ...)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="users.csv"'
writer = csv.writer(response)
writer.writerow(['username', 'First name', 'Last name', 'Email address'])
for user in users:
writer.writerow(user)
return response
回答2:
When you iterate over the queryset, you need to use:
for user in users:
writer.writerow(user.username, user.first_name, user.last_name, user.email)
来源:https://stackoverflow.com/questions/54641304/how-to-narrow-down-django-detailview-export-to-csv-file