【问题标题】:Updating multiple tables in Django在 Django 中更新多个表
【发布时间】:2021-10-19 05:04:33
【问题描述】:

我是 Django 和 DBMS 的新手。我有表 1 和表 2,我正在更新两者,如果表 1 成功更新,如果出现错误,我将进入更新表 2 的过程在更新表 2 时,我需要恢复我在表 1 中所做的更改。如何在 Django 中实现?

这是我大致做的代码

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!'})

【问题讨论】:

    标签: python-3.x django sqlite django-models django-rest-framework


    【解决方案1】:

    有一种非常有效的用法,称为原子块。更多信息和用法:docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 2013-10-14
      相关资源
      最近更新 更多