django multiple models save single commit -


in view, saving data in multiple models:

def myview(request):     #do processing     model1.save()     model2.save() 

how ensure there rollback of model1.save() in case model2.save() raises error. or how commit after both models saved?

in other words, "only save model1 , model2 if both save() successful"

use atomic transaction:

atomicity defining property of database transactions. atomic allows create block of code within atomicity on database guaranteed. if block of code completed, changes committed database. if there exception, changes rolled back.

examples:

from django.db import transaction  transaction.atomic():     model1.save()     model2.save() 

and

from django.db import transaction  try:     transaction.atomic():         model1.save()         model2.save() except integrityerror:     handle_exception() 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -