2013-02-22 71 views
6

我对django和Python相当陌生,希望能够导出我的模型中的项目列表,即产品。我正在看这里的文档 - https://docs.djangoproject.com/en/dev/howto/outputting-csv/将项目从模型导出为CSV Django/Python

我想我需要将需要创建一个变量,存储所有我想要的数据。但不确定它会在上面链接的代码片段中的位置。

道歉,因为这是一个非常不好的问题,但真的任何帮助。

下面是代码给我的脚本至今:

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"' 

回答

10

看一看的python csv module

你可能想要得到的车型领域与

def get_model_fields(model): 
    return model._meta.fields 

然后使用

getattr(instance, field.name) 

获取字段值(如this问题)。

然后你就会想是

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) 

这是一个有点冗长(和未经测试),但它应该给你一个想法。 (哦,别忘了关闭你的文件)

+0

发现可以用 “在obj._meta.get_all_field_names()用于现场:”。可能会更简洁一点。 – 2014-04-28 17:07:17

2

你也可以制作一个模板来帮助格式化!

模板是一种常见的Django模板

from django.template import loader 
def export_to_csv(request): 
    response = HttpResponse(mimetype='text/csv') 
    response['Content-Disposition'] = 'attachment; filename="products-list.csv"' 
    template = loader.get_template('templates/products_template.csb') 
    response.write(template.render(Context({'products': Products.objects.all()}))) 
    return response 
12

根据不同的情况 - 你可能希望你的模型的CSV。如果你有机会到Django管理站点,你可以在显示为列表中的任何模型常规操作插头(谷歌:Django管理行动)

http://djangosnippets.org/snippets/790/

如果你使用一个控制台操作(python manage.py ... ),你可以使用这样一个脚本,我只是用:

(把它放在:yourapp /管理/命令/ model2csv.py)

""" 
Prints CSV of all fields of a model. 
""" 

from django.core.management.base import BaseCommand, CommandError 
import csv 
import sys 

class Command(BaseCommand): 
    help = ("Output the specified model as CSV") 
    args = '[appname.ModelName]' 

    def handle(self, *app_labels, **options): 
     from django.db.models import get_model 
     app_name, model_name = app_labels[0].split('.') 
     model = get_model(app_name, model_name) 
     field_names = [f.name for f in model._meta.fields] 
     writer = csv.writer(sys.stdout, quoting=csv.QUOTE_ALL) 
     writer.writerow(field_names) 
     for instance in model.objects.all(): 
      writer.writerow([unicode(getattr(instance, f)).encode('utf-8') for f in field_names]) 

这并不捕获任何异常等,但作为管理员,你不会造成他们被提出,对吧?

这样使用它:

./manage.py model2csv my_ecommerce.Product > products.csv 
+0

如果其中一个属性是外键,它似乎不起作用。对于这样的属性,我得到'id unknown'形式的值,其中'id'是外键值(例如'1 unknown')。对我而言,'field_names = [f.attname for f in model._meta.fields]''。 – silentser 2016-01-11 13:04:39

+0

我建议在queryset上使用select_related。如果你有外键,你将会有大量的SQL查询。 '例如在model.objects.all()中。select_related(): writer.writerow([unicode(getattr(instance,f))。encode('utf-8')for f in field_names])' – maykel 2017-06-23 08:46:10