python - When using Django save() to update db, exception is thrown but why is db still updated? -


here models , views file. objective add new attribute db ("entries") added models , make migrations using python manage.py commands. worked , had new attribute correct default "na" in it. wanted read file , use column update db correct values. "worked" except after .save() command executed updated db correctly still threw exception error , left try block.

i tried searching see if else had same issue , read through documentation on django's site save() [https://docs.djangoproject.com/en/1.9/topics/db/models/]

i wondering why , if else has had issue , can tell me in future fix problem.

the way know db updated afterwards ran "data.objects.all()" , on each 1 printed out "probes" , "entries" see changed na file was.

thanks help.

models.py

class data(models.model):     probes = models.charfield(primary_key=true, max_length=50)     entries = models.charfield(max_length=25, default="na")     symbol = models.charfield(max_length=50)     pattern = models.charfield(max_length=25)     day1 = models.floatfield()     day3 = models.floatfield()      class meta:         unique_together = (('probes', 'symbol', 'pattern'),) 

views.py

def testupdatedb(passfilename):  f = open(passfilename, 'r')  line in f:     line = line.replace('\r',"")     line = line.replace('\n', "")      row = line.split(",")      arylist = {"probes": row[0],                "entries":row[2],                "symbol": row[3],                "pattern":row[4],                "day1":   row[5],                "day3":   row[6]                }     try:         # update database         t = data.objects.get(probes=arylist["probes"])          print(t.probes + " has " + t.entries + " entries, updating " + arylist["entries"])          t.entries = arylist["entries"]         t.save()          u = data.objects.get(probes=arylist["probes"])          print(u.probes + " has " + u.entries + " entries now. update sussess!")      except:         print("could not find: " + arylist["probes"]) 

in views.py right after/during "t.save()" program skips exception block , prints out message. afterwards can @ db , see updated correctly, why did exception happen? why didn't entire try block finish? else have error when trying update database.

try using transaction.atomic() if error occurs code present within block rolled back. nothing saved unless whole block executes.

it documented examples in link above, try use save() inside atomic transaction.


Comments