顧名思義,這是一個用於處理導入和導出數據的庫。django-import-export庫支持多種格式,包括xls、csv、json、yaml以及tablib支持的全部其餘格式。它還有一個Django管理集成,使用起來很是方便。javascript
使用PIP安裝css
pip install django-import-export
更新settings.py:html
INSTALLED_APPS = ( ... 'import_export', )
還有一個可選的配置,我一般這樣添加:java
IMPORT_EXPORT_USE_TRANSACTIONS = True
默認值爲False。它肯定庫是否會在數據導入中使用數據庫事務,以確保安全。python
django-import-export庫使用Resource的概念,它的類定義很是相似於Django處理模型表單和管理類的方式。nginx
在文檔中,做者建議將與資源相關的代碼放在admin.py文件。可是,若是實現與Django admin沒有關係,我一般更喜歡在app文件夾裏建立一個名爲resources.py。sql
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.pydjango
from import_export import resources from .models import Person class PersonResource(resources.ModelResource): class Meta: model = Person
這是最簡單的定義。您能夠將幾個配置傳遞給元類,如:fields
, exclude
json
導出數據到CSV
from .resources import PersonResource person_resource = PersonResource() dataset = person_resource.export() dataset.csv
id,name,email,birth_date,location 1,John,john@doe.com,2016-08-11,Helsinki 2,Peter,peter@example.com,2016-08-11,Helsinki 3,Maria,maria@gmail.com,2016-08-11,Barcelona 4,Vitor,vitor@freitas.com,2016-08-11,Oulu 5,Erica,erica@gmail.com,2016-08-11,Oulu
導出數據到JSON
dataset.json
[
{"id": 1, "name": "John", "email": "john@doe.com", "birth_date": "2016-08-11", "location": "Helsinki"}, {"id": 2, "name": "Peter", "email": "peter@example.com", "birth_date": "2016-08-11", "location": "Helsinki"}, {"id": 3, "name": "Maria", "email": "maria@gmail.com", "birth_date": "2016-08-11", "location": "Barcelona"}, {"id": 4, "name": "Vitor", "email": "vitor@freitas.com", "birth_date": "2016-08-11", "location": "Oulu"}, {"id": 5, "name": "Erica", "email": "erica@gmail.com", "birth_date": "2016-08-11", "location": "Oulu"} ]
導出數據到YAML
dataset.yaml
- {birth_date: '2016-08-11', email: john@doe.com, id: 1, location: Helsinki, name: John} - {birth_date: '2016-08-11', email: peter@example.com, id: 2, location: Helsinki, name: Peter} - {birth_date: '2016-08-11', email: maria@gmail.com, id: 3, location: Barcelona, name: Maria} - {birth_date: '2016-08-11', email: vitor@freitas.com, id: 4, location: Oulu, name: Vitor} - {birth_date: '2016-08-11', email: erica@gmail.com, 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: john@doe.com, id: 1, location: Helsinki, name: John} - {birth_date: '2016-08-11', email: peter@example.com, 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,jessica@jones.com,2016-08-11,New York, Mikko,mikko@suomi.com,2016-08-11,Jyväskyla,
id必須存在,由於它是主鍵。可是它會生成,因此咱們不須要指定值。
import.html
{% extends 'base.html' %}
{% block content %}
<form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% 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.