Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating multiple tables in Django

I'm new to Django, and DBMS .I have table 1 and table 2, I'm updating both and if table 1 was successfully updated, i ll move to the process of updating table 2 , if there was an error while updating table 2, then i need to revert the changes i made in table 1. how can i achieve that in Django?

This is the code i did roughly

def user_operation(request, id):    
if request.method == 'PUT':
        try:
            json_fetch = json.loads(request.body)
            update_emp = EmpDetailsModel.objects.get(emp_id=id)
            for key,value in json_fetch.items():
                flag = 0
                if key == 'contact':
                    cont_update = EmpDetailsModel.objects.get(emp_id=id)
                    for contact in value:
                        flag = cont_update.empcontactmodel_set.create(phone_number=contact['number'], dev_type=contact['type'])
                    if flag == 0: return JsonResponse({'Error':'There was an Error !'})
                    continue
                flag = update_emp.update(**{key:value}) 
                if flag == 0: return JsonResponse({'Error':'There was an Error !'})

        except KeyError:
            return JsonResponse({'Error':'Invalid Key in request!'})
like image 716
Jeesson Johney Avatar asked Sep 07 '25 04:09

Jeesson Johney


1 Answers

There is a very efficiently usage which called atomic block. For more information and usages : docs

like image 101
jackquin Avatar answered Sep 10 '25 14:09

jackquin