search
HomeBackend DevelopmentPython Tutorialpython Django批量导入数据

前言:

这期间有研究了Django网页制作过程中,如何将数据批量导入到数据库中.

这个过程真的是惨不忍睹,犯了很多的低级错误,这会在正文中说到的.再者导入数据用的是py脚本,脚本内容参考至自强学堂--中级教程--数据导入.

 注:本文主要介绍自己学习的经验总结,而非教程!

正文:首先说明采用Django中bulk_create()函数来实现数据批量导入功能,为什么会选择它呢?

1 bulk_create()是执行一条SQL存入多条数据,使得导入速度更快;

2 bulk_create()减少了SQL语句的数量;

       然后,我们准备需要导入的数据源,数据源格式可以是xls,csv,txt等文本文档;

       最后,编写py脚本,运行即可!

py脚本如下:

#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 LOrder

f = open('cs.csv')
WorkList = []
next(f) #将文件标记移到下一行
for line in f:
  parts = line.replace('"','') #将字典中的"替换空
  parts = parts.split(';') #按;对字符串进行切片
  WorkList.append(LOrder(serv_id=parts[0], serv_state_name=parts[1], acct_code=parts[2], acct_name=parts[3], acc_nbr=parts[4], user_name=parts[5],
              frod_addr=parts[6], mkt_chnl_name=parts[7],mkt_grid_name=parts[8], com_chnl_name=parts[9],com_grid_name=parts[10],
              product_name=parts[11],access_name=parts[12], completed_time=parts[13],remove_data=parts[14], service_offer_name=parts[15],
              org_name=parts[16], staff_name=parts[17],staff_code=parts[18], handle_time=parts[19],finish_time=parts[20],
              prod_offer_name=parts[21],eff_date=parts[22], exp_date=parts[23],main_flag=parts[24], party_name=parts[25]
              )
          )
f.close() 
LOrder.objects.bulk_create(WorkList)

根据上面py脚本源代码主要来说说自己学习过程中遇见的问题

问题1:需要导入的数据源中其第一行一般是字段名,从第二行开始才是数据,所以在脚本利用next(f)将文本标记移到第二行进行操作,不然会出现问题,比如字段名一般为英文,默认是字符串格式化,脚本执行就会遇见ValidationError:YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]这种models数据格式与导入数据格式不相符合的错误!

问题2:注意parts = parts.split(';') #按;对字符串进行切片该语句,因为我们导入数据每一行中的每列数据之间有间隔符,例如csv中逗号,xls中空格等各种文本默认间隔符号,split函数使用实例如下:

以下实例展示了split()函数的使用方法: 

#!/usr/bin/python

str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( );
print str.split(' ', 1 ); 

以上实例输出结果如下: 

['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
问题3:如果导入数据源超过10M,然后数据库默认最大10M,那么上面脚本运行不会成功.以mysql为例,若导入数据大小超过数据设置,那么会报2006 go away错误,需要在mysql中的my.ini中的[mysqld]下加入下列语句:

max_allowed_packet=300M --最大允许包大小300M
wait_timeout=200000  --连接时间200000s
interactive_timeout = 200000 --断开时间200000s

以上就是本文的全部内容,希望对大家学习python批量导入数据有所帮助。

Statement
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
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools