Praful Bagai
Praful Bagai

Reputation: 17382

How to undo last transactions in Django DB

Well, I've a data in a csv file which is to be inserted in the DB. Now I cannot guarantee that the data provided will be according to my needs, so I want if there is any exception, then the previous transactions on the DB should be undo.

What I currently do is that the data is saved till an exception is found. I throw the exception and then prints the exception at the line number. What I want is that the whole file should be inserted again without any duplicate rows. How can I do it?

Here is my code:-

for row in rows:
    line += 1
    try : 
        obj = XYZ(col1 = row[0],col2=row[1])
        obj.save()
    except : raise ("Excetion found at line ", line)

How should I undo all the previous transactions which were done before an exception arised??

Upvotes: 0

Views: 525

Answers (1)

yuvi
yuvi

Reputation: 18427

Sounds like what you're looking for is atomic(), to quote the docs (emphasis mine):

Atomicity is the defining property of database transactions. atomic allows us to create a block of code within which the atomicity on the database is guaranteed. If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back.

Upvotes: 2

Related Questions