我正在尝试弄清楚如何将数据简单导出到CSV文件。我找到了一个可行的示例。...
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
上面的代码按预期工作,将所有用户从User.objects.all()导出到电子表格。但是,我试图从DetailView做到这一点,并且仅使用.all()获取正在查看的用户的数据,而不是整个模型的数据。
从我收集的数据来看,为了在DetailView中执行此操作,我相信我需要做类似的事情...
class ExportDataDetailView(LoginRequiredMixin,DetailView):
model = Author
context_object_name = 'author_detail'
...。然后也许我需要重写get_queryset?不过,这似乎有些矫kill过正,因为我已经在DetailView中了。
感谢任何正确方向的指针。
答案 0 :(得分:1)
使用DetailView
时,表示只能使用对象。如果要导出该文件,可以执行以下操作:
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
现在,如果要获取所有用户的数据,则可以使用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
答案 1 :(得分:0)
遍历查询集时,需要使用:
for user in users:
writer.writerow(user.username, user.first_name, user.last_name, user.email)