Django import export实现数据库导入导出方式

所属分类: 脚本专栏 / python 阅读数: 1759
收藏 0 赞 0 分享

使用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界面实现导入导出

自定义导出 方式 action 这种方式也推荐

import xlwt
#导出Excel
from django.http import StreamingHttpResponse
class AdminReport(admin.ModelAdmin):
 actions = ["saveexecl"]     # 自定义的action(导出到excel表格)
 list_display = ("id",'offer','day_time', 'idfa', 'submit_result_text', 'callback_result_text') # 显示的列
 search_fields = ('day_time','callback_result_text')  # 可以搜索的字段
 date_hierarchy = 'day_time'  # 按照日期显示
 list_filter = ('offer',)   # 过滤条件
 list_per_page = 500    # 每页显示500条,太多了可能会出现服务器崩掉的情况
 
 def saveexecl(self,request,queryset):
  Begin = xlwt.Workbook()
  sheet = Begin.add_sheet("response")
  cols = 0
  for query in queryset:
   # you need write colms      # 好像有个方法可以一次性写入所有列,记不清了,只能用这种简单的方法去实现
   sheet.write(cols,1,str(query.idfa))  # 写入第一列
   sheet.write(cols,2,str(query.day_time)) # 写入第二列
   sheet.write(cols,3,str(query.keyword))  # 写入第三列
   cols += 1
  Begin.save("%s" %(filename))
  def file_iterator(filename,chuck_size=512):
   with open(filename,"rb") as f:
    while True:
     c = f.read(chuck_size)
     if c:
      yield c
     else:
      break
  response = StreamingHttpResponse(file_iterator(filename))
  response['Content-Type'] = 'application/octet-stream'
  response['Content-Disposition'] = 'attachment;filename="{}"'.format("result.xls")
  return response
 saveexecl.short_description = "导出Excel"   # 按钮显示名字


admin.site.register(Report, AdminReport)  # 注册到admin

以上这篇Django import export实现数据库导入导出方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

pandas的qcut()方法详解

这篇文章主要介绍了pandas的qcut()方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

从列表或字典创建Pandas的DataFrame对象的方法

这篇文章主要介绍了从列表或字典创建Pandas的DataFrame对象的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

pandas.DataFrame的pivot()和unstack()实现行转列

这篇文章主要介绍了pandas.DataFrame的pivot()和unstack()实现行转列,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

pandas中的series数据类型详解

这篇文章主要介绍了pandas中的series数据类型详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

pandas 时间格式转换的实现

这篇文章主要介绍了pandas 时间格式转换的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

python中时间、日期、时间戳的转换的实现方法

这篇文章主要介绍了python中时间、日期、时间戳的转换的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

pandas进行时间数据的转换和计算时间差并提取年月日

这篇文章主要介绍了pandas进行时间数据的转换和计算时间差并提取年月日,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

详解将Pandas中的DataFrame类型转换成Numpy中array类型的三种方法

这篇文章主要介绍了详解将Pandas中的DataFrame类型转换成Numpy中array类型的三种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

python和c语言的主要区别总结

在本篇文章里小编给各位整理了关于python和c语言的主要区别的相关知识帖内容,有需要的朋友们学习阅读下。
收藏 0 赞 0 分享

选择Python写网络爬虫的优势和理由

在本篇文章里小编给各位整理了一篇关于选择Python写网络爬虫的优势和理由以及相关代码实例,有兴趣的朋友们阅读下吧。
收藏 0 赞 0 分享
查看更多