[英]How I can Do a transaction rollback and commit at the time of import
The code given below is the program to import data into my django model, actually what this program does is it read the file and it import each line from the file to the django model, here may be 1000 files will be there,there will be some error in some file and the program will catch the exception if the file have any type of error and log it, But what i need is to rollback the entire transaction from one file which throws an error.I want to do this in postgres 下面给出的代码是将数据导入到我的django模型中的程序,实际上该程序所做的是读取文件,并将文件中的每一行导入到django模型中,这里可能有1000个文件,一些文件中的一些错误,如果文件有任何类型的错误并将其记录下来,程序将捕获异常,但是我需要的是从一个引发错误的文件中回滚整个事务,我想在postgres中做到这一点
def impSecOrdr_File(self,path):
lines=1
try:
fromFile=open(path)
for eachLine in fromFile:
obj = SecOrdr_File()
if lines!=1:
fieldsInline = eachLine.split(",")
obj.dates = dates
obj.column1 = fieldsInline[0].strip()
obj.column2 = fieldsInline[1].strip()
obj.column3 = float(fieldsInline[2].strip())
obj.column4 = float(fieldsInline[3].strip())
obj.save()
lines+=1
except BaseException as e:
transaction.rollback()
logging.info('\tError in importing %s line %d : %s' % (path, lines, e.__str__()))
else:
try:
logging.info("\tImported %s, %d lines" % (path, lines))
except Exception as e:
logging.info(e)
Is there any way to do that. 有没有办法做到这一点。 I went through the django transaction document and I tried Some of these but it is not working.. Can any one help me please
我浏览了django交易文档,并尝试了其中的一些方法,但是它不起作用。
you can save the obj into a list use a try statement if all the transaction passes the save the transactions 您可以将obj保存到列表中,如果所有事务都通过了try语句,则保存交易
lis =[]
try:
#your code
lis.append(obj) #instead of obj.save()
except:
#catch the error and transaction get cancelled
else:
k=len(lis)
for i in range(k):
lis[i].save()
I will suggest you to use postgresSQL instead of sqlite 我建议您使用postgresSQL代替sqlite
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.