将项目从模型导出到CSV Django/Python [英] Exporting items from a model to CSV Django / Python
问题描述
我对django和Python相当陌生,希望能够导出我的模型(即产品)中的项目列表.我在这里查看文档- https://docs.djangoproject.com/en/dev/howto/output-csv/
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.com/en/dev/howto/outputting-csv/
我想我需要创建一个变量来存储我想要的所有数据.但不确定上面链接的代码片段中的位置.
I'm persuming I need will need to create a variable that stores all the data that I want. But not sure where it would within the snippet of code on the link above.
道歉,因为这是一个非常讨厌的问题,但对您真的有帮助.
Apologies as this is a very noobish question but would really Any help at all.
这是到目前为止我脚本的代码:
Here is the code to my script so far:
import csv
from products.models import Product
from django.http import HttpResponse
def export_to_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="mytest.csv"'
推荐答案
看看 python csv模块.
您可能希望使用来获取模型字段
You'll probably want to get the models fields with
def get_model_fields(model):
return model._meta.fields
然后使用
getattr(instance, field.name)
获取字段值(如此问题).
to get the field values (as in this question).
然后,您将需要
with open('your.csv', 'wb') as csvfile:
writer = csv.writer(csvfile)
# write your header first
for obj in YourModel.objects.all():
row = ""
for field in fields:
row += getattr(obj, field.name) + ","
writer.writerow(row)
这有点冗长(未经测试),但是应该可以给您一个想法.(哦,别忘了关闭文件)
It's a bit verbose (and untested), but it should give you an idea. (Oh and don't forget to close your file)
这篇关于将项目从模型导出到CSV Django/Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!