V.Khakhil
V.Khakhil

Reputation: 265

Save model with @transaction.atomic in class based view

I am trying to handle both add new and edit object. My views.py file is like-

personal_data=Personal.objects.create(emp_fname=first_name, emp_mname=middle_name, emp_lname=last_name)
# rest of object is created here
try: 
    print "pk", pk
    with transaction.atomic(): 
        if pk != None:
            print "hey"
            #save model goes here
            messages.add_message(request, messages.INFO, 'Data updated successfully')
        else:
            print "hello"
            personal_data.save()
            family_data.save()
            address_data.save()
            education_data.save()
            pre_company_data.save()
            messages.add_message(request, messages.INFO, 'Data saved successfully')
except IntegrityError: 
    handle_exception() 

if-else condition works properly but data is saved in both cases. even if I commented the code shown above still data goes to database.

Upvotes: 3

Views: 780

Answers (1)

Stefano Cianciulli
Stefano Cianciulli

Reputation: 307

If you mean that personal_data is saved in both cases, it is because you're calling Personal.objects.create, which creates and saves the model in the database in one step (reference: https://docs.djangoproject.com/en/dev/topics/db/queries/#creating-objects). If you want to separate the creation from the save, create the model using the usual constructor:

personal_data = Personal(emp_fname=first_name, emp_mname=middle_name, emp_lname=last_name)

try:
    with transaction.atomic(): 
    if pk != None:
        # do stuff
    else:
        personal_data.save()
        # do some other stuff
except IntegrityError: 
    handle_exception() 

In this case, the personal_data model will be saved only in the else branch.

Upvotes: 1

Related Questions