Installation and configuration — django-import-export 3.3.4.dev0 documentation
pip install django-import-export
INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'baseapps.apps.BaseappsConfig', #或者使用 baseapps
'mdeditor',
'import_export', #加入应用
]
在app所在目录下创建resource.py,代码定义两个类
from import_export import resources
from baseapps.models import topic,documentes
class topicResource(resources.ModelResource):
class Meta:
model = topic
class documentesResource(resources.ModelResource):
class Meta:
model = documentes
修改admin.py,修改的地方就是把我们定义的Admin类原本继承的admin.ModelAdmin改成ImportExportModelAdmin
from django.contrib import admin
from baseapps.resource import topicResource,documentesResource #添加resource.py中的类
from baseapps.models import topic,documentes
from import_export.admin import ImportExportModelAdmin #导入导出功能
# Register your models here.
class topicAdmin(ImportExportModelAdmin): # ExportMixin导出,ImportMixin导入,ImportExportModelAdmin导入导出
resource_class = topicResource # 引入设定的导出字段,现在是全部
admin.site.register(topic,topicAdmin)
# class docAdmin(admin.ModelAdmin):
class docAdmin(ImportExportModelAdmin): # ExportMixin导出,ImportMixin导入,ImportExportModelAdmin导入导出
list_display = ('title','author','date_added','topic') # ModelAdmin列表页展示的字段名
search_fields = ('title','author',) #添加“标题”查询
list_filter = ('topic',) # 直接激活过滤器
resource_class =documentesResource ## 引入设定的导出字段
admin.site.register(documentes,docAdmin) # docAdmin只有注册后才能使用
export_order
是导出的字段顺序,fields
是定义字段导入(注意字段是否能为空)
class documentesResource(resources.ModelResource):
class Meta:
model = documentes
fields = ('id', 'topic', 'title', 'date_added','text',) #定义需要导入哪些字段
export_order = ('id', 'title','topic', 'date_added','text',) #定义导出的字段顺序
exclude = ['id'] #导入时排除id主键
import_id_fields = ['id'] #定义主键id,这样在id同样的情况下就是更新而不是增加新记录了
id = Field(attribute='id', column_name='编号') #定义导出时列名为中文'编号'
name = Field(attribute='title', column_name='书籍名称')
# 定义导出时列名为中文'标题',也可以用column_name=documentes.title.field.verbose_name