Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

252
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda