简体   繁体   English

如何使用django-import-export将数据从csv导入模型?

[英]How to import data from csv to models using django-import-export?

I've made some researches about django-import-export, but the most of example I have found are using django admin.. I'm trying to import data to a django model from my template (when clicking on a button a modal appears to choose file location and then submit ), 我已经对django-import-export进行了一些研究,但我发现的大多数例子都是使用django admin ..我正在尝试从我的模板导入数据到django模型(当点击按钮时出现模态选择文件位置,然后提交),

I feel lost and I don't know how to start.. 我感到迷茫,我不知道如何开始......

This is the model I have : 这是我的模型:

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100) 

could someone guide me by giving the steps to follow ? 有人可以通过采取步骤来指导我吗?

Thanks in advance ! 提前致谢 !

I have not used django-import-export but writing a view for CSV generation is not difficult using python's built-in csv module. 我没有使用过django-import-export,但使用python的内置csv模块编写一个用于CSV生成的视图并不困难。

Django docs also have a section on outputting csv . Django文档也有一节关于输出csv

Following is a snippet based on example provided in docs: 以下是基于docs中提供的示例的代码段:

import csv
from django.http import HttpResponse
from django.views.generic import View

class CsvExportView(View):

    def get(self, request):
        # create a response object
        response = HttpResponse(content_type='text/csv')
        # assign a filename for csv
        response['Content-Disposition'] = 'attachment; filename="{}"'.format("filename.csv")
        wr = csv.writer(response, dialect='excel')
        # get queryset
        queryset = Musician.objects.all()
        # write every queryset to response object
        for obj in queryset:
            row = [obj.first_name, obj.last_name, obj.instrument]
            wr.writerow(row)
        # return response object
        return response

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM