如果 python 中没有错误,我如何保存整个数据库事务

How can I save the whole DB transaction if there is no error in python

我在一个文件夹中有很多文件我打开文件夹并将所有文件中的所有数据导入我的模型,这里我的程序一次导入一个文件中的数据,因此它将读取文件一次,我遍历每行末尾的每一行我使用 obj.save().

将事务保存到数据库

这里我遇到了一些异常,因为导入可能会出现类型不匹配错误,因此程序会停止导入该文件,并且将导入一半数据并将其移动到下一个文件。所以这个问题导致重复数据所以在这里我需要使用文件的 obj.save() 保存事务如果没有异常我怎么能实现这个任何人都可以帮助我

        fromFile=open(path)
        for eachLine in fromFile:
            obj = SAMP()
            fieldsInline = eachLine.split(",")
            n=len(fieldsInline)
            if lines!=1:
            #obj.dates =  dates
                obj.col1 = fieldsInline[0].strip()
                obj.col2 = fieldsInline[1].strip()
                obj.col3 = fieldsInline[2].strip()
                obj.col4 = fieldsInline[3].strip()

                obj.save() 
            lines+=1

        except BaseException as e:
            logging.info('\tError in importing %s line %d : %s' % (path, lines, e.__str__()))
        else: 
            logging.info("\tImported %s, %d lines" % (path, lines))       

您可以使用 transaction.

所以你的函数应该变成这样:

from django.db import transaction

@transaction.commit_on_success
def func():
    pass

或:

from django.db import transaction

def func():
    # Some code
    with transaction.commit_on_success():
        pass

If the function returns successfully, then Django will commit all work done within the function at that point. If the function raises an exception, though, Django will roll back the transaction.