“Django”;writer.writerow“;每列
我正在尝试分别获取每一列。但我还是找不到正确的分区。我的代码添加到下面。我试图应用一个循环,更改列表的格式,但没有效果 我在论坛上寻找答案,但是下面的代码对我根本不起作用“Django”;writer.writerow“;每列,django,csv,Django,Csv,我正在尝试分别获取每一列。但我还是找不到正确的分区。我的代码添加到下面。我试图应用一个循环,更改列表的格式,但没有效果 我在论坛上寻找答案,但是下面的代码对我根本不起作用 #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(requ
#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
期望值
您在这里使用而不是。因此,csv编写器将'Id'
和'username'
解释为两行(单独的):
writer.writerow(('Id','Username','Email','Password'))
users=CustomUser.objects.all().values\u列表('id','username','email','password'))
writer.writerows(用户)
请注意,通常不使用.values\u list()
或.values()
来序列化数据。通常最好使用序列化程序,因为这样可以更容易地进行双向序列化/解析,并进一步添加额外的逻辑来进行序列化
writer.writerow(('Id', 'Username', 'Email', 'Password'))
users = CustomUser.objects.all().values_list('id', 'username', 'email', 'password')
writer.writerows(users)