0

我正在使用 Python 3.5、Django 1.8 和 PostgreSql 9.4。

所以我有一种编辑方法,在获取请求中我正在呈现表单,当用户提交表单时它会得到更新。她的密码

def edit_case(request, case_id):
    case = get_object_or_404(Case, pk=case_id)
    if request.method == 'POST':
        data = request.POST.copy()
        form = CaseEditForm(data, instance=case)
        if form.is_valid():
            res = form.save()
            return HttpResponseRedirect(reverse("case_list"))
    else:
        form = CaseEditForm(instance=case)
    variables = RequestContext(request, {
        "form": form,
    })
    return render_to_response(
        'sample/edit_case.html',
        variables,
    )

现在我想在其上添加行级锁定,例如如果一个用户同时更新某些内容,除非先前的事务成功,否则其他用户将无法更新任何内容,或者如果有人有任何其他更好的建议,而不是使用悲观锁定。

我知道select_for_update但不知道在以下情况下如何实施form.save()

任何帮助将非常感激

4

1 回答 1

1

After so much research I have figured out the solution. So now while getting queryset against id I am using "select_for_update", something like this

with transaction.atomic():
    case = get_object_or_404(Case.objects.select_for_update(), pk=case_id)
    form = CaseEditForm(data, instance=case)
        if form.is_valid():
            res = form.save()
            return HttpResponseRedirect(reverse("case_list"))

So as you can see now I am fetching the query set object under the transaction and if any exception appear during transaction it will automatically rollback and Also as I am using select_for_update so it will lock the row until the transaction get succeeded or failed.

If anyone have better suggestion then kindly share it.

于 2016-11-25T09:43:47.567 回答