2013-02-22 87 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