Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

255
Views
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.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!