将项目从模型导出到CSV Django / Python

时间:2013-02-22 17:13:14

标签: python django django-models python-3.x

我是django和Python的新手,希望能够导出我的模型中的项目列表,即产品。我在这里查看文档 - https://docs.djangoproject.com/en/dev/howto/outputting-csv/

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

道歉,因为这是一个非常愚蠢的问题,但确实会有任何帮助。

到目前为止,这是我脚本的代码:

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 个答案:

答案 0 :(得分:12)

查看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)

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

答案 1 :(得分:12)

根据具体情况,您可能希望获得模型的CSV。如果您可以访问Django Admin站点,则可以为显示为列表的任何模型插入通用操作(google:django admin actions)

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

如果您使用控制台(python manage.py ...)进行操作,则可以使用我刚才使用的脚本:

(将其放入:yourapp / management / commands / 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

答案 2 :(得分: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

答案 3 :(得分:2)

我在代码中使用它。它有效,并且只需要在 model_class 变量中定义模型类。 此Django视图允许使用下载CSV。 CSV名称为 Django_app.model_name.csv

import csv

from django.http import HttpResponse

from .models import Trade


def export_to_csv(request):
    # The only line to customize
    model_class = Trade

    meta = model_class._meta
    field_names = [field.name for field in meta.fields]

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta)
    writer = csv.writer(response)

    writer.writerow(field_names)
    for obj in model_class.objects.all():
        row = writer.writerow([getattr(obj, field) for field in field_names])

    return response

答案 4 :(得分:1)

根据@ tomasz-gandor的回答,这是一个潜在的解决方案,但已更新至2020年:

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

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


class Command(BaseCommand):
    help = ("Output the specified model as CSV")


    def add_arguments(self, parser):
        parser.add_argument('model',
                            nargs=1,
                            type=str,
                            help='Model name to export, like <app.model> or "members.Member"')
        parser.add_argument('outfile',
                            nargs=1,
                            type=str,
                            help='Save path, like </path/to/outfile.csv> or "/data/members.csv"')


    def handle(self, *app_labels, **options):
        from django.apps import apps
        app_name, model_name = options['model'][0].split('.')
        model = apps.get_model(app_name, model_name)
        field_names = [f.name for f in model._meta.fields]
        writer = csv.writer(open(options['outfile'][0], 'w'), quoting=csv.QUOTE_ALL, delimiter=',')
        writer.writerow(field_names)
        for instance in model.objects.all():
            writer.writerow([str(getattr(instance, f)) for f in field_names])

可以轻松用于:

python manage.py model2csv members.Member /data/members_export.csv

答案 5 :(得分:0)

使用django.db.models.query.QuerySet.values可以针对我的用例进行更优化的查询。

import csv
from datetime import datetime

from django.http import HttpResponse

# Populate this list with your model's fields
# Replace MODEL with your model
fields = [f.name for f in MODEL._meta.fields]

# The following code will live inside your view
timestamp = datetime.now().isoformat()

response = HttpResponse(content_type="text/csv")
response[
    "Content-Disposition"
] = f"attachment; filename={timestamp}.csv"
writer = csv.writer(response)

# Write the header row
writer.writerow(fields)

# Replace MODEL with your model
for row in MODEL.objects.values(*fields):
    writer.writerow([row[field] for field in fields])

return response

答案 6 :(得分:0)

我合并了以前的一些答案,因为我需要从生产中导入一些数据,并在此过程中更改其中的一些数据。所以这是我的解决方案,您可以在编写CSV文件时覆盖某些字段值。

将一些查询集数据导出到CSV文件中:

import csv

from myapp.models import MyModel
from user.models import User

# Make some queryset manually using Django shell:
user = User.objects.get(username='peterhil')
queryset = MyModel.objects.filter(user=user)

def query_to_csv(queryset, filename='items.csv', **override):
    field_names = [field.name for field in queryset.model._meta.fields]
    def field_value(row, field_name):
        if field_name in override.keys():
            return override[field_name]
        else:
            return row[field_name]
    with open(filename, 'w') as csvfile:
        writer = csv.writer(csvfile, quoting=csv.QUOTE_ALL, delimiter=',')
        writer.writerow(field_names)  # write the header
        for row in queryset.values(*field_names):
            writer.writerow([field_value(row, field) for field in field_names])

# Example usage:
query_to_csv(queryset, filename='data.csv', user=1, group=1)

答案 7 :(得分:0)

将此解决方案用于csv文件模型。可能会有所帮助

 # 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

答案 8 :(得分:0)

如果您不关心字段名,而是想要所有字段,请执行此操作。

A = [1, 3, 5, 0, 0];
B = [0, 2, 6, 0, 1];

const res = A.map((a, i) => Math.min(a, B[i]) || Math.max(a, B[i]));

console.log(res)

答案 9 :(得分:0)

我使用了 django-queryset-csv 包。

请按照以下步骤操作:

  1. pip install django-queryset-csv

  2. 您的 views.py:

<块引用>
import djqscsv
from products.models import Product

def get_csv(request):
    qs = Product.objects.all()
    return djqscsv.render_to_csv_response(qs)