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!'})
There is a very efficiently usage which called atomic block. For more information and usages : docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With