顾名思义,这是一个用于处理导入和导出数据的库。django-import-export库支持多种格式,包括xls、csv、json、yaml以及tablib支持的所有其他格式。它还有一个Django管理集成,使用起来非常方便。
使用PIP安装
pip install django-import-export
更新settings.py:
INSTALLED_APPS = ( ... 'import_export', )
还有一个可选的配置,我通常这样添加:
IMPORT_EXPORT_USE_TRANSACTIONS = True
默认值为False。它确定库是否会在数据导入中使用数据库事务,以确保安全。
Resources
django-import-export库使用Resource的概念,它的类定义非常类似于Django处理模型表单和管理类的方式。
在文档中,作者建议将与资源相关的代码放在admin.py文件。但是,如果实现与Django admin没有关系,我通常更喜欢在app文件夹里创建一个名为resources.py。
models.py
from django.db import models class Person(models.Model): name = models.CharField(max_length=30) email = models.EmailField(blank=True) birth_date = models.DateField() location = models.CharField(max_length=100, blank=True)
resources.py
from import_export import resources from .models import Person class PersonResource(resources.ModelResource): class Meta: model = Person
这是最简单的定义。您可以将几个配置传递给元类,如:fields
, exclude
导出数据
导出数据到CSV
from .resources import PersonResource person_resource = PersonResource() dataset = person_resource.export() dataset.csv
id,name,email,birth_date,location 1,John,[email protected],2016-08-11,Helsinki 2,Peter,[email protected],2016-08-11,Helsinki 3,Maria,[email protected],2016-08-11,Barcelona 4,Vitor,[email protected],2016-08-11,Oulu 5,Erica,[email protected],2016-08-11,Oulu
导出数据到JSON
dataset.json
[ {"id": 1, "name": "John", "email": "[email protected]", "birth_date": "2016-08-11", "location": "Helsinki"}, {"id": 2, "name": "Peter", "email": "[email protected]", "birth_date": "2016-08-11", "location": "Helsinki"}, {"id": 3, "name": "Maria", "email": "[email protected]", "birth_date": "2016-08-11", "location": "Barcelona"}, {"id": 4, "name": "Vitor", "email": "[email protected]", "birth_date": "2016-08-11", "location": "Oulu"}, {"id": 5, "name": "Erica", "email": "[email protected]", "birth_date": "2016-08-11", "location": "Oulu"} ]
导出数据到YAML
dataset.yaml
- {birth_date: '2016-08-11', email: [email protected], id: 1, location: Helsinki, name: John} - {birth_date: '2016-08-11', email: [email protected], id: 2, location: Helsinki, name: Peter} - {birth_date: '2016-08-11', email: [email protected], id: 3, location: Barcelona, name: Maria} - {birth_date: '2016-08-11', email: [email protected], id: 4, location: Oulu, name: Vitor} - {birth_date: '2016-08-11', email: [email protected], id: 5, location: Oulu, name: Erica}
过滤数据
from .resources import PersonResource from .models import Person person_resource = PersonResource() queryset = Person.objects.filter(location='Helsinki') dataset = person_resource.export(queryset) dataset.yaml
- {birth_date: '2016-08-11', email: [email protected], id: 1, location: Helsinki, name: John} - {birth_date: '2016-08-11', email: [email protected], id: 2, location: Helsinki, name: Peter}
视图的例子
导出到CSV视图
from django.http import HttpResponse from .resources import PersonResource def export(request): person_resource = PersonResource() dataset = person_resource.export() response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="persons.csv"' return response
导出到Excel视图
from django.http import HttpResponse from .resources import PersonResource def export(request): person_resource = PersonResource() dataset = person_resource.export() response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="persons.xls"' return response
导入数据
查看new_persons.csv的数据:
name,email,birth_date,location,id Jessica,[email protected],2016-08-11,New York, Mikko,[email protected],2016-08-11,Jyväskyla,
id必须存在,因为它是主键。但是它会生成,所以我们不需要指定值。
import.html
{% extends 'base.html' %} {% block content %}{% endblock %}
views.py
from tablib import Dataset def simple_upload(request): if request.method == 'POST': person_resource = PersonResource() dataset = Dataset() new_persons = request.FILES['myfile'] imported_data = dataset.load(new_persons.read()) result = person_resource.import_data(dataset, dry_run=True) # Test the data import if not result.has_errors(): person_resource.import_data(dataset, dry_run=False) # Actually import now return render(request, 'core/simple_upload.html')
在admin.py里使用ImportExportModelAdmin
,而不是ModelAdmin
from import_export.admin import ImportExportModelAdmin from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(ImportExportModelAdmin): pass
添加之后刷新页面你就会看到导入和导出按钮。
在导入现有项目时,导入功能具有良好的差异性:
这是一个大的Django库。你可以用它做更多的事情。它的文档完全值得一看:API reference.