Exporting items from a model to CSV Django / Python

前端 未结 9 2045
死守一世寂寞
死守一世寂寞 2021-02-03 09:52

I\'m fairly new to django and Python and want to be able to export a list of items in my model i.e products. I\'m looking at the documentation here - https://docs.djangoproject.

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-03 10:45

    Use this solution for model csv file.might being helpful

     # Create the HttpResponse object with the appropriate CSV header.
     response = HttpResponse(content_type='text/csv')
     response['Content-Disposition'] = 'attachment; 
     filename="somefilename.csv"'
     writer = csv.writer(response);
     writer.writerow(["username","Email"]);
     for i in User.objects.all():
         writer.writerow([i.username,i.email])
     return response
    

提交回复
热议问题