python Django批量导入不重复数据

WBOY
Release: 2016-06-10 15:05:30
Original
1136 people have browsed it

本文为大家分享了python Django批量导入不重复数据的实现代码,供大家参考,具体内容如下

程序如下:

#coding:utf-8 

import os 
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "www.settings") 

'''
Django 版本大于等于1.7的时候,需要加上下面两句
import django
django.setup()
否则会抛出错误 django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
'''
import django
import datetime


if django.VERSION >= (1, 7):#自动判断版本
 django.setup()

from keywork.models import DevData 

f = open('cs.csv')
WorkList = []
next(f) #将文件标记移到下一行
x = y = 0
for line in f:
 parts = line.replace('"','') #将字典中的"替换空
 parts = parts.split(',') #按;对字符串进行切片
 if DevData.objects.filter(serv_id = parts[0],day_id=parts[24]).exists():
  x = x + 1
 else:
  y = y + 1
  WorkList.append(DevData(serv_id=parts[0], serv_state_name=parts[1], acc_nbr=parts[2], user_name=parts[3], acct_code=parts[4], product_id=parts[5],
       mkt_chnl_name=parts[6], mkt_chnl_id=parts[7],mkt_region_name=parts[8], mkt_region_id=parts[9],mkt_grid_name=parts[10],
       sale_man=parts[11],sale_outlets_cd1_name=parts[12], completed_time=parts[13],remove_data=parts[14], user_flag=parts[15],
       pro_flag=parts[16], service_offer_id=parts[17],service_offer_name=parts[18], finish_time=parts[19],staff_name=parts[20],
       staff_code=parts[21],org_name=parts[22],prod_offer_name=parts[23],day_id=parts[24]
       ))
f.close() 
DevData.objects.bulk_create(WorkList)
print "重复数据"+str(x)+"条,成功导入数据"+str(y)+"条"
Copy after login

本文主要运用模型中exists()判断导入数据和数据库是否重复,如果不重复就用bulk_create批量导入数据库!

可对照参考我的另一篇文章:批量导入数据

以上就是本文的全部内容,希望对大家的学习有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template