首页 > 解决方案 > 每列的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

期望

在此处输入图像描述

标签: djangocsv

解决方案


您在这里使用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()化数据。通常最好使用序列化器,因为这样可以更轻松地进行双向序列化/解析,此外还可以添加额外的序列化逻辑。


推荐阅读