django 导入Excel文件 ORM 批量操作

导入excel文件后批量插入"bulk_create"方法

1.先定义数据模型

from django.db import models
from django.utils.translation import ugettext_lazy as _

ACTIVE_TYPE = (
    (1, _(u"已激活")),
    (0, _(u"未激活")),
)


class Unit(models.Model):
    """
    社会单位
    """
    id = models.AutoField(primary_key=True, editable=False)
    name = models.CharField(_(u"单位名称"), max_length=100, unique=True, db_index=True)
    address = models.CharField(_(u"单位地址"), max_length=100, null=True, blank=True, db_index=True)
    contactperson = models.CharField(_(u"联系人"), max_length=30, null=True, blank=True, db_index=True)
    contactnumber = models.CharField(_(u"联系人电话"), max_length=30, null=True)
    rc_group_id = models.CharField(_(u"融云群组ID"), default=uuid.uuid1, editable=False, max_length=36)
    rc_group_name = models.CharField(_(u"融云群组名"), max_length=50, null=True, editable=True)
    longitude = models.DecimalField(_(u"经度"), max_digits=9, decimal_places=6, null=True, blank=False, default=31.184111)
    latitude = models.DecimalField(_(u"纬度"), max_digits=9, decimal_places=6, null=True, blank=False, default=121.58611)
    active = models.SmallIntegerField(_(u"状态"), choices=ACTIVE_TYPE, db_index=True, null=False, editable=False, default=1)
    device_operation_password = models.CharField(_(u"操作密码"), max_length=4, editable=True, null=True)
    map_title = models.CharField(_(u"地图标题"), max_length=30, null=True, blank=True, db_index=True) 
    

2.下面是导入excel文件返回字典数据,用字典来接收数据是因为"Unit"的name属性为unique,所有用name作为key值去重

# coding: utf-8
import xlrd
import uuid
import random


def excel_table_by_name(file_excel='/home/kevin/下载/danwei_11.xlsx',
                        col_name_index=0, by_name=u'Sheet1'):
    """
        根据名称获取Excel表格中的数据
        参数: file_excel:Excel文件路径
             col_name_index:表头列名所在行的所以
             by_name:Sheet1名称
    """
    data = xlrd.open_workbook(file_excel)
    table = data.sheet_by_name(by_name)
    n_rows = table.nrows   # 行数
    col_names = table.row_values(col_name_index)  # 某一行数据
    row_dict = {}
    for row_num in range(1, n_rows):
        row = table.row_values(row_num)
        row_dict[row[0]] = row[1]
    return row_dict

def import_unit_batch():
    data = excel_table_by_name()
    from ..models.model_unit import Unit
    # from ..models.model_appname import AppName
    # from ..models.model_monitor import Monitor, BRANCH_TYPE_DICT
    unit_list = []
    # app_names = AppName.objects.filter(id__in=(12, 13))
    for k, v in data.items():
        longitude_latitude = v.split(',')
        unit_obj = Unit.objects.filter(name=k)
        if not unit_obj:
            new_unit = Unit(
                contactnumber='13' + str("%09d" % random.randint(0, 999999999)),
                longitude=longitude_latitude[1],
                latitude=longitude_latitude[0],
                rc_group_id=uuid.uuid1(),
                rc_group_name=k,
                active=1,
                device_operation_password='1718',
                name=k,
                map_title='地图',
            )
            unit_list.append(new_unit)
    Unit.objects.bulk_create(unit_list)

excel 的格式为

单位 经纬度
单位1 121.6455545,29.56565
单位2 121.6455545,29.56566


3.批量更新对象,以下代码相当于 update unit where id >= 703;

>>> from mysite.manage.models.model_unit import Unit
>>> units = Unit.objects.filter(id__gte=703)
>>> units.update(map_title='更改地图标题')
983L
>>> units[0].map_title
u'\u66f4\u6539\u5730\u56fe\u6807\u9898'
>>> print u'\u66f4\u6539\u5730\u56fe\u6807\u9898'
更改地图标题
>>> 

 

4.批量删除对象,以下代码相当于 delete from unit where id >= 703;

>>> from mysite.manage.models.model_unit import Unit
>>> units = Unit.objects.filter(id__gte=703)
>>> len(units)
983
>>> units.delete()
>>> units
[]
>>> 

 

posted @ 2016-10-14 16:24  嫁给幸福  阅读(7183)  评论(0编辑  收藏  举报