django-import-export的文档在如何配置管理员以从电子表格导入方面有点薄弱。有人有完整的例子吗?
问问题
6729 次
2 回答
3
这不是一个完整的模块。但你可以理解它应该是怎样的。
资源.py 文件
from import_export import resources
from .models import edxUser
class edxUserResource(resources.ModelResource):
class Meta:
model = edxUser
#skip_unchanged = True
#report_skipped = True
#if you want to exclude any field from exporting
exclude = ('id','edx_anonymized_id')
fields = ('id', 'edx_id', 'edx_anonymized_id', 'edx_email', 'edx_name', 'time_created', 'created_by')
#Order of the export fields
export_order = ('edx_id', 'edx_email')
admin.py 文件
from import_export.admin import ImportExportModelAdmin
from django.contrib import admin
from .models import edxUser
from resources import edxUserResource
@admin.register(edxUser)
class edxUserAdmin(ImportExportModelAdmin):
resource_class = edxUserResource
模型.py 文件
from __future__ import unicode_literals
from django.conf import settings
from django.db import models
class edxUser(models.Model):
edx_id = models.IntegerField('edX user id', blank=True, null=True)
edx_anonymized_id = models.IntegerField("edX anonymized user id", blank=True, null=True)
edx_email = models.EmailField('edx user email', max_length=75, blank=True)
edx_name = models.CharField('edx name', max_length=75, blank=True, null=True)
time_created = models.DateField('Created time', blank=True, null=True)
created_by = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)
def __unicode__(self):
return str(self.edx_id)
于 2017-07-08T05:53:46.657 回答
1
下面是如何做到这一点,假设电子表格中的列名是Title
和Field one
。此示例假定模型实例将在每次导入时重新创建(而不是通过主键更新)。
from django.contrib import admin
from import_export.admin import ImportMixin
from import_export import resources, fields
from .models import MyModel
class MyModelResource(resources.ModelResource):
title = fields.Field(attribute='title',
column_name='Title')
field_one = fields.Field(attribute='field_one',
column_name='Field one')
def get_instance(self, instance_loader, row):
# Returning False prevents us from looking in the
# database for rows that already exist
return False
class Meta:
model = MyModel
fields = ('title', 'field_one')
export_order = fields
class MyModelAdmin(ImportMixin, admin.ModelAdmin):
resource_class = MyModelResource
admin.site.register(MyModel, MyModelAdmin)
于 2015-09-09T15:28:10.477 回答