django插件之django-import-export

Posted zlixing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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,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 %

% csrf_token %



% 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

 

django插件之django-import-export_导出

 

以上是关于django插件之django-import-export的主要内容,如果未能解决你的问题,请参考以下文章

django入门8之xadmin引入富文本和excel插件

Django之权限管理插件

Django自定制插件之随机验证码

django-debug-toolbar 之 内存信息的插件pympler

Django-Form组件之字段

Django之DjangoAdmin