Django import / export实现数据库导入导出

折月煮酒 提交于 2021-01-06 11:31:52

使用django-import-export库,导入导出数据,支持csv、xls、json、html等格式

官网:http://django-import-export.readthedocs.io/en/latest/installation.html

1、安装django-import-export

pip install django-import-export

2、配置settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'customer',
    'publisher',
    'import_export',
)

执行命令: python manage.py collectstatic

3、models.py 建立model

class Author(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name


class Category(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name


class Book(models.Model):
    name = models.CharField('Book name', max_length=100)
    author = models.ForeignKey(Author, blank=True, null=True)
    author_email = models.EmailField('Author email', max_length=75, blank=True)
    imported = models.BooleanField(default=False)
    published = models.DateField('Published', blank=True, null=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    categories = models.ManyToManyField(Category, blank=True)

    def __unicode__(self):
        return self.name

4、在admin.py 创建Resource、对应的Admin

from import_export import resources
from core.models import Book
from import_export.admin import ImportExportModelAdmin


class BookResource(resources.ModelResource):

    class Meta:
        model = Book
        export_order = ('id', 'name', 'author', 'author_email', 'imported', 'click', 'published', 'price', 'categories')

@admin.register(Book)
class BookAdmin(ImportExportModelAdmin):
    list_display = ('name', 'author', 'author_email', 'imported', 'published', 'price', 'categories')
    search_fields = ('name', 'author','published')
    date_hierarchy = 'date'   
    resource_class = BookResource

export_order:设置导出字段的顺序

5、Django界面实现导入导出

自测发现,导出xlsx格式不支持,其他正常。

 

 

 

 

 

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!