django - 每列的Django“writer.writerow”
问题描述
我正在尝试分别获取每一列。但我仍然无法得到正确的划分。我的代码添加在下面。我尝试应用循环,更改列表的格式但无济于事。
我在论坛中寻找答案,但下面的代码对我根本不起作用。
#My try
wr.writerow(item) #column by column (everything goes to one column)
wr.writerows(item) #row by row (divides my word into parts)
def export_users_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="users.csv"'
writer = csv.writer(response)
writer.writerows(('Id', 'Username', 'Email', 'Password'))
users = CustomUser.objects.all().values_list('id', 'username', 'email', 'password')
for user in users:
writer.writerow(user)
return response
期望
解决方案
您在这里使用writerows
[python-doc]而不是writerow
[python-doc]。因此 csv 编写器将'Id'
, 和解释'username'
为两个(单独的)行:
writer.writerow(('Id', 'Username', 'Email', 'Password'))
users = CustomUser.objects.all().values_list('id', 'username', 'email', 'password')
writer.writerows(users)
请注意,通常不使用或.values_list()
序列.values()
化数据。通常最好使用序列化器,因为这样可以更轻松地进行双向序列化/解析,此外还可以添加额外的序列化逻辑。
推荐阅读
- java - 反向链接列表,同时保留原始节点
- bash - 查找具有给定祖先的提交
- rust - 如何解决可变借用和不可变借用的共存问题?
- numbers - python库快速生成上一个和下一个素数
- atom-editor - 自动大写关键字(对于 SQL)?
- javascript - 如何通过单击使工具提示隐藏?
- android - 电子邮件意图 - 与此操作关联的所有应用程序均已关闭、阻止或未安装
- python - Python:将嵌套列表的整数元素添加到列表中
- wordpress - Wordpress REST API,如何获取 /post 架构?
- django - 没有名为“django.urls”的模块