1. 程式人生 > 其它 >django外掛之django-import-export

django外掛之django-import-export

文件:https://django-import-export.readthedocs.io/en/latest/getting_started.html#creating-import-export-resource

顧名思義,這是一個用於處理匯入和匯出資料的庫。django-import-export庫支援多種格式,包括xls、csv、json、yaml以及tablib支援的所有其他格式。它還有一個Django管理整合,使用起來非常方便

安裝:

pip install django-import-export

配置:

settings.py檔案

INSTALLED_APPS = (
    ...
    
'import_export', )

# 預設值為False。它確定庫是否會在資料匯入中使用資料庫事務,以確保安全。
IMPORT_EXPORT_USE_TRANSACTIONS=True

Resources

django-import-export庫使用Resource的概念,它的類定義非常類似於Django處理模型表單和管理類的方式。

在文件中,作者建議將與資源相關的程式碼放在admin.py檔案。但是,如果實現與Django admin沒有關係,我通常更喜歡在app資料夾裡建立一個名為resources.py。

model.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

  •   fields = ('appid',) : 指定匯出的欄位
  • export_order = ('appid','name') : 指定匯出的順序
  • exclude = ('appid',) : 不用匯出的內容
  • import_id_fields = ('ID',) :指定ID欄位名稱

匯出資料:

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 %}
  <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')

Django後臺管理

在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