Exporting items from a model to CSV Django / Python

前端 未结 9 2043
死守一世寂寞
死守一世寂寞 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:33

    If you don't care about fieldnames and want all the fields, just do this.

    with open('file_name.csv', 'w') as csvfile:
        writer = csv.writer(csvfile)
        for obj in YourModel.objects.values_list():
            row = list(obj)
            writer.writerow(row)
    

提交回复
热议问题